Socket.io fires connect event just after the second connect - node.js

I'm using socket.io with the latest version of node.js and socket.io shows an curious behavior:
The connect event fires on client side but not on server side for the first time.
After a reload or simply loading the page again the event got fired on both - client and server - side correctly.
What's wrong (with my code?)?
// Client
var socket = io.connect(window.location.protocol + '//' + window.location.hostname, {
'sync disconnect on unload': true
});
socket.on('connect', function() {
alert("Connect");
// Do other stuff
});
-
// Server
io.sockets.on('connection', function(socket) {
console.log("connection");
io.sockets.on('connect', function(socket) {
console.log("connect");
});
});
Started the server and loaded the page:
Client fires the alert, server just logs connection. Now loading the page again, it logs both connection and connect.
Update:
It seems that just the very first connection has such issues, afterwards it works everywhere as expected. Just after every node server (re)start, that behavior appears.
Note: node itself delivers the page where the socket.io is used and that works even on the first request, so a node issue should be excluded then.
Browser is also doesn't matter, it's the same on every browser.

For Socket.IO, connection is the server-side equivalent of connect on the client side. Therefore, when you're inside the callback for the connection event, the socket has already established a connection and you don't need to listen on some other event. I'm not sure what connect on the server side is, but it is not documented and does not work.
// on the server
io.sockets.on('connection', function(socket) {
// this connection has already been established
// no other handler is required
});
// on the client
var socket = io.connect();
socket.on('connect', function() {
// the connection has been established
});

Related

socket.io-client web socket connection failing in node.js child process

I am using simple socket.io client module to connect to web socket but the connection is failing. The way I have learned is that right after you define socket, you can access connected property to find out the status of connection and it always return false. I am trying to connect to web socket in a child process on the same server where my main process is running.
var socket = require('socket.io-client')("ws://xx.xx.xxx.xxx");
console.log(socket.connected);
SocketIO connections should be initiated over HTTP(S):
var socket = require('socket.io-client')('http://localhost:6001');
(instead of ws://...)
Then wait for the connect event; when that fires, the client is connected to the server;
socket.on('connect', function() {
console.log('connected to server!');
...
});

Socket.io client behavior when server is unreachable

I was wondering what is the default behavior when socket.io-client can't connect to the server and no callback is provided on the error.
Does the client indefinitely try to reconnect until it can reach the server?
I noticed that If I run this code on client before launching the server. As soon as the latter is started it receives the 'doSomethig' evnt.
socket.on('connect', function () {
socket.emit('doSomething', data);
socket.destroy();
});
How can I prevent the server to receive data emitted before it was started?
socket.on('connect_error', function () { socket.destroy(); });

Create web socket streams between a server and arbitrary NodeJS processes

Having a server running on localhost:5000, I want to connect to that server from another NodeJS process, via web sockets.
From my experience with web sockets, I always needed the server object to create a web socket server.
var http = require('http');
// create http server
var server = http.createServer(function(req, res) {
// serve files and responses
...
});
// Socket.io server listens to our app
var io = require('socket.io').listen(server);
// Send current time to all connected clients
function sendTime() {
io.sockets.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
socket.emit('welcome', { message: 'Welcome!' });
socket.on('i am client', console.log);
});
server.listen(3000);
This is a tiny example using socket.io. Without having access to get the server variable (since this server will be deployed some where in the cloud), how can I connect via web sockets to this server?
An ugly solution would be via HTTP requests, but that's not web sockets. I want to keep the connection open and pipe data there.
How can I do that?
You get the socket.io-client module, require() it into your other nodejs server and use that client module from your other server (which will be the client in this case) and connect from that server to this one.
Example code here: https://github.com/automattic/socket.io-client
var socket = require('socket.io-client')('http://localhost');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});

Leaking sockets (sockets.io)

I have a client that connects to a socket server (node.js). I seem to being leaking sockets.
Here is the flow that causes the leaked sockets.
Connect to socket server
Signout (I see the log out confirmation on the server)
Signin in again to the socket server (see confirmation on socket server)
Restart socket server quickly (force restart using supervisor module by resaving a file)
Client reconnects to socket server. I now see 2 sockets that have connected to the socket server, instead of what should be just one.
If I repeat steps 2-4, I can see multiple connections from the same client.
Here is my client socket.io code:
client.js:
function start_socket(tok){
console.log("socket trying to connect");
//try every second to reconnect
socket = io.connect(sockets_host, { query: $.param({token: tok}), 'forceNew' : true, 'reconnection limit' : 100, 'max reconnection attempts' : 'Infinity' });
socket.on('connect', function() {
console.log('connected to socket server');
set_loggedin_status('true');
});
socket.on('disconnect', function() {
console.log('disconnected from server');
set_loggedin_status('false');
close_socket(); //get leaked sockets, wether I call this or not, though less if I do...
});
socket.on('error',function(err){
console.log('socket error: ' + err);
attempt_login();
});
}
function close_socket(){
console.log("in close socket");
socket.disconnect(true);
set_loggedin_status('false');
}
I've tried the above without 'forceNew' : true,, but then I seem to have problems signing in again after the client signed-out.
If I call close_socket from within the disconnected event (and not just from elsewhere when the client chooses to signout), I seem to get fewer leaked sockets, but still get them.
How am I creating multiple sockets?
The solution, though not necessarily the answer to the question, was in my case to use socket.io.disconnect() instead of socket.disconnect().
However, this meant if the socket server goes down once i've already established a connection, that no reconnects were being tried. So, I have to handle this situation myself if using this approach to solve the leaking sockets.

Socket.IO is not triggering the connect event

I'm trying to setup a Socket.IO server, and right now, connecting doesn't seem to be working the way it does in the Wiki. I'm connecting to a server using the namespace /client, and I'm successfully seeing the connection made in the debug log, but the connection message is never display (and the other contents are never getting attached).
Server-side
var clients = io
.of('/client')
.on('connect', function (socket) {
// This is never getting run
console.log('Client connected');
});
Client side
var socket = io.connect('http://localhost:8082/client');
Why, in the above code, am I not getting the 'Client connected' message in my console?
So, turns out this is a very simple issue, as I suspected. The client uses the connect event, but the server uses connection.
The code should look like:
var clients = io
.of('/client')
.on('connection', function (socket) {
// This is never getting run
console.log('Client connected');
});

Resources