Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect two node.js servers with websockets?

Here's my problem:

I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.

However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.

So, this is the case I'm striving for:

.--------.      .----------.      .----------. | CLIENT | <--> | SERVER A | <--> | SERVER B | '--------'      '----------'      '----------' 

Client-server A connection is done through socket.io

Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...

Even the example code in socket.io-client module doesn't work... :/

// Connect to server var socket = new io.Socket('localhost', {port: 8080}); socket.connect();  // Add a connect listener socket.on('connect', function(socket) {      console.log('Connected.'); }); 

The code just passes without any errors and execution ends after few seconds.

Update: Code samples

Server (which works just fine) looks like this:

// Load requirements var http = require('http'),     io = require('socket.io');  // Create server & socket var server = http.createServer(function(req, res){      // Send HTML headers and message     res.writeHead(404, {'Content-Type': 'text/html'});     res.end('<h1>Aw, snap! 404</h1>'); }); server.listen(8080); io = io.listen(server);  // Add a connect listener io.sockets.on('connection', function(socket) {       console.log('Client connected.');      // Disconnect listener     socket.on('disconnect', function() {         console.log('Client disconnected.');     }); }); 

Client looks like this

console.log('1');  // Connect to server var io = require('socket.io-client') var socket = new io.Socket('localhost', {port: 8080}); socket.connect();  console.log('2');  // Add a connect listener socket.on('connect', function(socket) {      console.log('Connected!'); });  console.log('3'); 

1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits

Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".

like image 282
crappish Avatar asked Jan 12 '12 15:01

crappish


People also ask

How do I connect two node JS servers?

connect('http://localhost:8080', {reconnect: true}); console. log('2'); // Add a connect listener socket. on('connect', function(socket) { console. log('Connected!

Does NodeJS support WebSockets?

Node. js can maintain many hundreds of WebSockets connections simultaneously. WebSockets on the server can become complicated as the connection upgrade from HTTP to WebSockets requires handling. This is why developers commonly use a library to manage this for them.

How many WebSocket connections can a NodeJS server handle?

The theoretical limit is 65k connections per IP address but the actual limit is often more like 20k, so we use multiple addresses to connect 20k to each (50 * 20k = 1 mil).


2 Answers

Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.

Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!

Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:

console.log('1');  // Connect to server var io = require('socket.io-client') var socket = io.connect('localhost:8080', {reconnect: true});  console.log('2');  // Add a connect listener socket.on('connect', function(socket) {      console.log('Connected!'); });  console.log('3'); 
like image 169
crappish Avatar answered Oct 08 '22 07:10

crappish


For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.

Required package is:

npm install socket.io 

Node-App-1 server.js:

var io = require('socket.io').listen(3000); io.on('connection', function (socket) {     console.log('connected:', socket.client.id);     socket.on('serverEvent', function (data) {         console.log('new message from client:', data);     });     setInterval(function () {         socket.emit('clientEvent', Math.random());         console.log('message sent to the clients');     }, 3000); }); 

Node-App-2 client.js:

var io = require('socket.io-client'); var socket = io.connect("http://localhost:3000/", {     reconnection: true });  socket.on('connect', function () {     console.log('connected to localhost:3000');     socket.on('clientEvent', function (data) {         console.log('message from the server:', data);         socket.emit('serverEvent', "thanks server! for sending '" + data + "'");     }); }); 
like image 28
Bagherani Avatar answered Oct 08 '22 06:10

Bagherani