WebSocket negotiation in Node.JS, Socket.IO and clusters does not work

I had a problem clustering my application with Node.js, socket.io and Node.js. clans

I use socket.io-redis to exchange information for all workers, but it does not work.

My code is:

var cluster = require('cluster'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', function(worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); }); } else { ... var express = require("express"); //Server var server = express(); //Socket.io var http = require('http').Server(server); var io = require('socket.io')(http); var redis_io = require('socket.io-redis'); var redis = require("redis"); io.adapter(redis_io({host: "127.0.0.1", port: 6379 })); ... } 

In the client, I get handshake errors like error 400 or WebSocket closes before the connection is established.

What can I do to solve this problem?

Im using the latest version of Node.js and socket.io

Thank!

+5
cluster-computing express
Oct. 15 '14 at 4:22
source share
2 answers

I had the same problem and it took me a while to figure this out. Few studies have explained that this is due to the fact that some of the transports, such as a lengthy survey, have to make several queries in order to establish the optimal connection. The requests have a state, therefore, if different consecutive requests are routed for different employees of the cluster, the connection fails.

On the page http://socket.io/docs/using-multiple-nodes/ there is a page that links to a custom cluster module called sticky-session that works around this: https://github.com/indutny/sticky- session

I really didn’t want to use it, because it basically ignores all the work that the node.js team invested in balancing TCP load behind the cluster module.

Since the Web Socket protocol requires only one connection, I managed to get around this by making websocket be the first and only transport. I can do this because I manage the client and server. For a public webpage, this may not be safe for you, as you need to worry about browser compatibility. In my case, the client is a mobile application.

Here is the JavaScript client code that I posted on my test page (again, the real client is a mobile application, so my web page is just help helping build and test):

 var socket = io('http://localhost:8080/', { transports: [ 'websocket' ] }); 
+19
Dec 07 '14 at 2:09
source share

You should use a sticky session to avoid connecting clients to different servers since the initial handshake. Submit this https://github.com/elad/node-cluster-socket.io

0
Aug 20 '19 at 9:40
source share



All Articles