pass port number to page loaded in node.js/socket.io - node.js

Okay, I have a simple test server set up using socket.io in node.js. My goal is to run the same server on a few different ports to test some load balanced conditions and synchronization tests.
Here is what the server looks like:
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
port = process.argv[1]; // listen on port number passed via command line
app.listen(port);
function handler (req, res) {
console.log('request', {remotePort: req.connection.remotePort, remoteAddress: req.connection.remoteAddress, url: req.url});
// how do I pass the port number here?
fs.readFile(__dirname + '/chat.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading chat.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
// do chatty stuff
});
The question is: what is the easiest way to get the port number into chat.html (see comment in code above)? Is there a way to do this with node or fs? Do I need to Express set up with templates?
Wonder what node will let me do with the query string; could I just stick the port in there and pick it out with jQuery once the page loads?
Thanks, in advance!

html is for static contents. so you can not use for dynamic contents.
so easiest way is using templates like ejs, jade and jquery template.
but you don't want you can change contents from chat.html
function(err, data) {
data = data.replace() // like this
}
I'm not recommend this way.

This is an old question, but decided to answer it with a more suiting answer still.
Because you're listening on the same port on both the http and socket.io, you can just change the script on the client to connect to the same address as the webpage was loaded, like so:
var socket = io.connect(window.location.href);
If the server was just a normal websocket server, you could do instead this:
var socket = new WebSocket(window.location.href.replace('http', 'ws'));

Related

Updating serial port data on webpage with Node JS

I am reading data from the serial port using Node JS (which I am quite new to at the moment). Although I can see the data through an stdout stream via console.log and get a static value on the webpage I cannot get the value to update on a continuous basis. My current code looks like this:
var http = require('http');
const SerialPort = require('serialport');
const Readline = require('#serialport/parser-readline');
const port = new SerialPort('/dev/ttyACM0', { baudRate: 9600 });
const parser = port.pipe(new Readline({ delimiter: '\r\n' }));
http.createServer(function (request, response) {
parser.on('data', (data) => {
console.log(data);
response.writeHead(200, {"Content-Type":"text/html"});
response.write(data);
});
}).listen(8888);
Is there a way I can get the serial data to update in realtime on the webpage as opposed to having to refresh the page?
Node JS version: v12.18.2
Depending on how often you want the page to update on the webpage, you could serve the most recent reading via an express api, or using something like socket io. Using express is a simpler but less real time. Socket io will be able to update in real time. https://socket.io/

Socket io on connection not connecting NodeJS

I just started learning NodeJS and I am trying to make a simple server-client project using Socket io.
What happens right now is that when I open localhost:8001, I don't see any logs inside the listener.sockets.on block.
var http = require('http');
var app = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('<h1>Hello!</h1>');
}).listen(8001);
var io = require('socket.io');
var listener = io.listen(app);
console.log("Sample Socket IO");
listener.sockets.on('connection', function (socket) {
console.log('a user connected');
socket.emit('connected', 'Welcome');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});
It looks like the logging will occur when a connection happens. You setup a listening socket, so try to connect to it. Try 'telnet 127.0.0.1 8001' to connect.
The browser page needs to load the socket.io client code for one thing. That is the first thing missing that I can see. Look through the example here http://socket.io/get-started/chat/ and make sure you are following exactly at first and then make changes after you get that example working. Your server code looks a bit different from their example also.

ConnectJS + RequireJS hanging after a few reloads

I got a fairly massive requirejs based app that runs unbundled locally. I have a few hundred js files that get loaded in async. This is pretty quick locally and generally not a big deal. After maybe 10->20 page refreshes connectjs starts hanging for some reason. I got a half decent message once when I opened a different page and chrome indicated "waiting for available socket."
I'm guessing that at some point something ends up hanging and the connection never ends. At some point enough of these connections results in Node + connect to not accept any more requests. Has anyone experienced this and what is the solution? Is there a way to time out or reject requests from the server side?
Here is my connectjs server script:
var connect = require('connect');
var http = require('http');
var app = connect()
.use(connect['static'](__dirname))
.use(function (req, res) {
'use strict';
res.setHeader('Access-Control-Allow-Origin', '*');
// used to stub out ajax requests
if (req.url.indexOf('ajax/') !== -1) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({}));
}
});
var server = http.createServer(app);
server.listen(3000, function () {
'use strict';
console.log('server is listening on port 3000');
});

How do I connect two Socket.io servers/apps?

I'm trying to build an application that has two components. There's a public-facing component and an administrative component. Each component will be hosted on a different server, but the two will access the same database. I need to set up the administrative component to be able to send a message to the public-facing component to query the database and send the information to all the public clients.
What I can't figure out is how to set up a connection between the two components. I'm using the standard HTTP server setup provided by Socket.io.
In each server:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
And on each client:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I've looked at this question but couldn't really follow the answers provided, and I think the situation is somewhat different. I just need one of the servers to be able to send a message to the other server, and still send/receive messages to/from its own set of clients.
I'm brand new to Node (and thus, Socket), so some explanation would be incredibly helpful.
The easiest thing I could find to do is simply create a client connection between the servers using socket.io-client. In my situation, the admin server connects to the client server:
var client = require("socket.io-client");
var socket = client.connect("other_server_hostname");
Actions on the admin side can then send messages to the admin server, and the admin server can use this client connection to forward information to the client server.
On the client server, I created an on 'adminMessage' function and check for some other information to verify where the message came from like so:
io.sockets.on('connection', function (socket) {
socket.on('adminMessage', function (data) {
if(data.someIdentifyingData == "data") {
// DO STUFF
}
});
});
I had the same problem, but instead to use socket.io-client I decided to use a more simple approach (at least for me) using redis pub/sub, the result is pretty simple. My main problem with socket.io-client is that you'll need to know server hosts around you and connect to each one to send messages.
You can take a look at my solution here: https://github.com/alissonperez/scalable-socket-io-server
With this solution you can have how much process/servers you want (using auto-scaling solution), you just use redis as a way to forward your messages between your servers.

httpServer in node.js to serve three.js

https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally suggests that three.js examples be served by a local server. The python SimpleHTTPServer works fine for me, except that I need to run it in the directory above the examples dir in the three.js repository clone.
Now I'm trying to serve up the same example using httpServer in node.js. I could use one of the node versions of SimpleHTTPServer, but I need a httpServer object to pass data from the server to the webgl browser example via socket.io. So I took the socket.io example and tried the following server.js to be run using node in the directory above examples.
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/examples/webgl_interactive_voxelpainter.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Net is that on 127.0.0.1:8080 with node I can't see the three.js example. The code doesn't work even if I remove all references to socket.io, indicating it's something about html.
What am I missing? The html file is being read properly because I don't get a callback error.
I noticed that the python server lists the directory as html links in the browser. I click examples to see the html files, then click the html file and it works fine. So I tried running the 'node server.js' one directory level up, with just about every combination of forward and backward slashes, root directory references,... to no avail.
I'm not hung up on pure httpServer. If express or something else works with socket.io and three.js, I'll board that train.
Use connect framework, makes your job easier.
var connect = require('connect');
var app = connect()
.use(connect.static('<your directory>'))
.use(function(req, res){
res.end();
})
.listen(8080);
http://www.senchalabs.org/connect/
https://github.com/senchalabs/connect

Resources