1
votes

Using socket.io and nodeJS cluster, looks like Websocket protocol fails and it falls back to long polling, any idea why it isnt using websocket?

This is the only error in console

WebSocket connection to 'ws://localhost:5050/socket.io/?EIO=3&transport=websocket&sid=82qh7nBXGusxyelJAAAG' failed: Connection closed before receiving a handshake response

Here is my node application

if (cluster.isMaster) {
    // we create a HTTP server, but we do not use listen
    // that way, we have a socket.io server that doesn't accept connections
    var server = require('http').createServer();
    var io = require('socket.io').listen(server);
    var redis = require('socket.io-redis');
    var fs = require('fs');

    io.adapter(redis({host: '127.0.0.1', port: 6379}));
    var i = 0;
    setInterval(function () {
        // all workers will receive this in Redis, and emit
        io.sockets.in('EURUSD').emit('message', 'EURUSD ' + i++);
        io.sockets.in('GBPUSD').emit('message', 'GBPUSD ' + i++);
    }, 1000);

    for (var i = 0; i < os.cpus().length; i++) {
        cluster.fork();
    }
    cluster.on('online', function (worker) {
        console.log("New Worker with ID ", worker.id);
    });

    cluster.on('exit', function (worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
}

if (cluster.isWorker) {
    var app = require('express')();
    var server = require('http').Server(app);
    var io = require('socket.io')(server);

    server.listen(config.port);

    var io = require('socket.io').listen(server);
    var redis = require('socket.io-redis');
    io.adapter(redis({host: '127.0.0.1', port: 6379}));


    io.sockets.on('connection', function (socket) {
        console.log('connected to worker id ', cluster.worker.id);
        socket.on('join', function (room) {
            socket.join(room);
        });

    });


    app.get("/", function (req, res) {
        res.sendFile('views/index.html', {root: __dirname});
    });
}

Client code

  var socket = io();
    socket.on('message', function (data) {
        var item = $('<li>' + data + '</li>');
        $('ul').prepend(item);
    });

    socket.emit("join", "GBPUSD");
1

1 Answers

0
votes

For those who may face similar issue, it turned out that I have the following line twice

var io = require('socket.io')(server);

Removing one, solved the issue.