Socket.io: failed: Connection closed before receiving a handshake response

Created on 9 Mar 2015  ·  21Comments  ·  Source: socketio/socket.io

Hi

I am using socket.io in project build on top of MEAN.IO (https://github.com/linnovate/mean) .
I integrated the library successfully , on my local everything is working fine with no errors in console.

but on deploying the same code on server it shows me an error as

WebSocket connection to 'ws://ip.ip.ip.ip:3000/socket.io/?EIO=3&transport=websocket&sid=OpeM3YIJqVuTnt-dAAAY' failed: Connection closed before receiving a handshake response

I had given options to socket for now to reconnect as : -

var socket = io.connect(baseUrl, {
'reconnection': true,
'reconnectionDelay': 1000,
'reconnectionDelayMax': 5000,
'forceNew': true
});

but still some times the socket remains inactive .

Handshakes

Most helpful comment

@nkzawa When using socket.io-redis(https://github.com/automattic/socket.io-redis), occasionally it may show the error message as follow:

WebSocket connection to 'ws://localhost:8501/socket.io/?EIO=3&transport=websocket&sid=WPOeefk2cs-DsfLFAAAE' failed: Connection closed before receiving a handshake response

Once this error occurred,then a http request would return 400.The error url is http://localhost:8501/socket.io/?EIO=3&transport=polling&t=1425998452675-5&sid=1VwKenkSONHg6-ddAABW,its return message was {"code":1,"message":"Session ID unknown"}.When i saw the log wirtten by server side , i found the socket 1VwKenkSONHg6-ddAABW had been disconnected.And at last the socket would not be able to reconnected successfully,and the client and server could not communicate with each other.

The code that i use :

var socketIo = require('socket.io');
var redis = require('socket.io-redis');
var socket_handler = require('./socket_handler');
var config = require('../config');
const PREFIX_SOCKET_IO = 'socketIoPrefix:';
function SocketIoApp(httpServer) {
    this.httpServer = httpServer;
}

SocketIoApp.prototype.listen = function(port) {
    var io = socketIo(this.httpServer);
    var redisConfig = config.redisConfig;
    redisConfig.key = PREFIX_SOCKET_IO;
    io.adapter(redis(redisConfig));
    this.httpServer.listen(port);

    io.on('connection', function (socket) {
        console.log('socketid',socket.id,'connected');
        socket.emit('hello','hello');
        socket.on('msg', function (data) {
            socket_handler.process(socket,data,function(err) {
               //
            });
        });
        socket.on('disconnect', function () {
            console.log(socket.id + ' disconnect');
        });
    });
    this.io = io;
}

All 21 comments

Do you have multiple server processes as your server? In that case, you have to use sticky session.

http://socket.io/docs/using-multiple-nodes/

@nkzawa : hi thank you so much for mentioning this i actually figure out that I am using Cluster with nodeJs in production mode which is breaking things on server . I try configuring the sticky-session (https://github.com/indutny/sticky-session) with my app as mention in nodeJs with clusteur section , which ultimately breaks my socket and now i am getting a console error as

Failed to open socket on port 5858, waiting 1000 ms before retrying
Failed to open socket on port 5858, waiting 1000 ms before retrying
Failed to open socket on port 5858, waiting 1000 ms before retrying
Failed to open socket on port 5858, waiting 1000 ms before retrying
Failed to open socket on port 5858, waiting 1000 ms before retrying

do you have any idea what am i missing :-(

@nkzawa When using socket.io-redis(https://github.com/automattic/socket.io-redis), occasionally it may show the error message as follow:

WebSocket connection to 'ws://localhost:8501/socket.io/?EIO=3&transport=websocket&sid=WPOeefk2cs-DsfLFAAAE' failed: Connection closed before receiving a handshake response

Once this error occurred,then a http request would return 400.The error url is http://localhost:8501/socket.io/?EIO=3&transport=polling&t=1425998452675-5&sid=1VwKenkSONHg6-ddAABW,its return message was {"code":1,"message":"Session ID unknown"}.When i saw the log wirtten by server side , i found the socket 1VwKenkSONHg6-ddAABW had been disconnected.And at last the socket would not be able to reconnected successfully,and the client and server could not communicate with each other.

The code that i use :

var socketIo = require('socket.io');
var redis = require('socket.io-redis');
var socket_handler = require('./socket_handler');
var config = require('../config');
const PREFIX_SOCKET_IO = 'socketIoPrefix:';
function SocketIoApp(httpServer) {
    this.httpServer = httpServer;
}

SocketIoApp.prototype.listen = function(port) {
    var io = socketIo(this.httpServer);
    var redisConfig = config.redisConfig;
    redisConfig.key = PREFIX_SOCKET_IO;
    io.adapter(redis(redisConfig));
    this.httpServer.listen(port);

    io.on('connection', function (socket) {
        console.log('socketid',socket.id,'connected');
        socket.emit('hello','hello');
        socket.on('msg', function (data) {
            socket_handler.process(socket,data,function(err) {
               //
            });
        });
        socket.on('disconnect', function () {
            console.log(socket.id + ' disconnect');
        });
    });
    this.io = io;
}

Hi I also have the same issue, Is there any solution for this???

Is this the same issue?

I see tons of errors, repeating every few seconds, and the app does not work at all (I am using socket.io-redis, with two websocket servers and rackspace load balancer, TCP_CLIENT_FIRST)

WebSocket connection to 'ws://some.domain.com:5001/socket.io/?EIO=3&transport=websocket' failed: Connection closed before receiving a handshake response

and I also have a log .on('connect_error', function...) on client side
every time the handshake error occurs, I get also:

Error: websocket error
    at WS.14.Transport.onError (http://192.168.1.72:9001/bower_components/socket.io-client/socket.io.js:2297:13)
    at WebSocket.19.WS.addEventListeners.ws.onerror (http://192.168.0.72:9001/bower_components/socket.io-client/socket.io.js:3436:10)

socket.io and socket.io-client libraries are both version 1.3.5

any ideas?

Looks like socket.io is conflicting when using more than 1 socket connection on a server. I have the same issues with livereload.

@nkzawa sticky-session published 2 years ago. it was reliable to use?

sticky-session and clones are serious and dangerously flawed as they use the incoming IP address for load balancing purposes and have no understanding for-forwarding headers so once you're ready to actually deploy in production and run your servers behind a load balancer as you want to run on multiple machines for redundancy purposes or just scale out, all node processes will receive the IP address of load balancer causing all requests to go to a single process.

So it's good for a temp solution, but not something that should be advised as an production ready solution.

@3rd-Eden do you have a solution in product environment or any article about it? thanks

@looping84 : Hi you can try out using Redis server with your application that helps me out .

Slightly related... another way you can get the same error string is by initializing the socket.io library twice. Boy I wish I could have those ten minutes of my life back :stuck_out_tongue: .

http://stackoverflow.com/questions/26665840/socket-io-failed-connection-closed-before-receiving-a-handshake-response

I wish my issue was that simple :( Still I don't blame anybody else but myself

@eremzeit I wish I could have those 2 hours of my life back :P
Thanks for the direction. It solved the problem.

it's work fine with ws but not working when change to wss.
My error message:

WebSocket connection to 'wss://iosock.dayl.toancauxanh.vn:5432/socket.io/?token=eyJ0eXAiOiJKV1QiLCJh…HA1JyERt24hP2TIa-chetqE&EIO=3&transport=websocket&sid=6QWsRBRMUi1_CcDZAAA8' failed: Connection closed before receiving a handshake response

Who help me? Regards

I've got the same problem, basically connecting double is what caused the error.

server.listen(8001);

/* io.listen(server);*/ <-- comment this

var listener = io.listen(server);
listener.sockets.on('connection', function(socket){
    socket.emit('message', {'message': 'hello world'});
});

Fixed the problem for me.

I was having this problem too and it turned out to be a configuration error in my webpack dev server proxy. The parameter ws: true was missing for the socket.io path. Adding that parameter fixed the problem.

Did you add ws: true in your webpack config?

I am getting this error, on ~ half of my socket.io connection attempts, when running my app in a cluster without sticky sessions.

My socket.io client is configured with transports: ['websocket'].

@nkzawa Given that I'm only using the websocket transport, I shouldn't need sticky sessions, right?

Has anyone seen this? I am getting this error in Safari, but not Chrome or Firefox. I'm using socket.io 2.0.4. This has been working for a long time, and I think Safari updated something. We're also using an Amazon ALB with HTTP/2 to help make this tricky.

Safari HTTP/2 400 WebSocket is closed before the connection is established.

In my case, the error occurred in browserSync.
To fix it, I needed to specify the parameter "ws: true" in browserSync options.

For example:
browserSync({
//...some options,
ws: true
})

In my case, I was using raw WebSocket

Was this page helpful?
0 / 5 - 0 ratings