Skip to content

Instantly share code, notes, and snippets.

@justindujardin
Created March 19, 2014 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justindujardin/9635073 to your computer and use it in GitHub Desktop.
Save justindujardin/9635073 to your computer and use it in GitHub Desktop.
Socket.IO: ERROR: "client not handshaken" explanation
/*
A simple socket.io client that will run server side and connect to the above server
repeatedly, for as long as you leave it running.
When the server runs with a low-latency Redis database, you will see nothing but
repeated "Connected" messages in the console. When the server connects to a Redis
data store that has even a modest amount of latency more than the client, you will
see some connections established properly, and others fail with the error:
ERROR: "client not handshaken"
*/
var io = require('socket.io/node_modules/socket.io-client');
function again(){
var socket = io.connect('http://localhost:4202',{
'force new connection':true
});
socket.on('connect',function() {
console.log("Connected");
socket.disconnect();
again();
});
socket.on('error',function(err){
console.log("ERROR: " + JSON.stringify(err));
});
}
again();
/*
A Simple socket.io server that will run with 4 cluster workers and connect to a
Redis database for its socket storage. This demonstrates the broken concurrency
model in Socket.IO that will prevent your app from ever scaling properly.
The issue is only apparent at massive scale, or when there is lower latency between
a client and the socket.io server than there is between the socket.io server and its
Redis database.
*/
"use strict";
var cluster = require('cluster');
if(cluster.isMaster){
for(var i = 0; i < 4; i++){
var worker = cluster.fork();
}
}
else {
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(4202);
io.set('transports', ['websocket']);
var RedisStore = require('socket.io/lib/stores/redis');
var redis = require('socket.io/node_modules/redis');
var createRedisClient = function(){
return redis.createClient();
// The below line to have redis connect to a remote server
// with a moderate amount of latency (~50ms reliably repro's on my MBP)
//return redis.createClient(6379,"redis.yourlaggyserver.net");
};
io.set('store', new RedisStore({
redisPub : createRedisClient(),
redisSub : createRedisClient(),
redisClient : createRedisClient()
}));
io.sockets.on('connection', function(socket) {
socket.disconnect();
});
}
@gabmontes
Copy link

@justindujardin Thanks for this! Very useful to reproduce the issue, understand what happens and figure out a fix. It is worth to note that v0.9.17 reduced significantly the amount of "client not handshaken" errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment