My node.js application uses TCP and Socket.io connections. It forwards data from TCP to relevant socket.io connections.
What I've noticed is, there is a minor delay while sending data over WebSockets (socket.io), not so significant during minimal payloads, but as the number of payloads increase the delay becomes significant.
Is this a known issue? A single publish on socket.io takes about 1.5secs.
Here's my code.
var net = require('net');
var httpServer = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8080);
console.log('Server running at http://127.0.0.1:1337/');
// The Socket.io jibber-jabber
var io = require('socket.io').listen(httpServer);
io.sockets.on('connection', function (socket) {
socket.emit('con',"Connected!");
socket.on('subscribe', function(data) { socket.join(data.room); });
socket.on('unsubscribe', function(data) { socket.leave(data.room); });
webSockets.push(socket);
console.log("Websocket connected.");
socket.on('disconnect', function () {
var index = webSockets.indexOf(socket);
webSockets = webSockets.splice(index,1);
console.log("Websocket disconnected.");
});
});
function SendToSocket(room, mssg)
{
console.log("--- Sending too rooms ---");
var time1 = new Date();
io.sockets.in(room).emit(room, mssg);
var time2 = new Date();
console.log(time1.getSeconds(),time1.getMilliseconds(),"---",time2.getSeconds(),time2.getMilliseconds());
}
var shortServer = net.createServer(function(c) { //'connection' listener
console.log('TCP client connected');
c.on('end', function() {
console.log('TCP client disconnected');
c.destroy();
});
c.on('data', function(data){
console.log(data);
SendToSocket('domain',data);
});
});
shortServer.listen(2501, function() { //'listening' listener
console.log('TCP Server bound');
});
The output is as follows
info - socket.io started
TCP Server bound
TCP client connected
<Buffer ff fb 1f ff fb 20 ff fb 18 ff fb 27 ff fd 01 ff fb 03 ff fd 03>
--- Sending too rooms ---
42 564 '---' 44 245
42 567 indicates seconds an microseconds respectively before the socket.io operation while 44 245 indicates time after operation. A lag of close to 2 secs.
The sendToSocket function is called whenever there is data on any TCP connection. I've timed the function and it takes close to 1.5secs to go through. Its the same if I don't use rooms, and use a simple for loop to send data to all socket connections.
More Details: Max message payload from TCP - 50 bytes. Max message payload to be sent on socket.io - 256 bytes OR chars. Frequency - as high as 3 times a second. No: of connections - Max 10.
P.S: During the test I noticed, even if I send a blank message from just one connection on TCP with no Socket.io connections; socket.io holds the app for 1.5secs during the call of SendToSocket