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

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!');
...
});

Related

Are sockets reused on reconnect event?

A socket is created when a user connects to the server.
The connection is broken because of interwebz malfunction.
Client reconnects automatically.
Will the socket connection be the same as when he first connected? Or will the socket be a new one?
Thanks!
A new connection is established on reconnect. It can be checked by printing the socket.id.
On server:
var io = require('socket.io)(server);
io.on('connection', function (socket) {
console.log('socket id is ' + socket.id); }
Excerpt from socket.io documentation
The property is present once the socket has connected, is removed when the socket disconnects and is updated if the socket reconnects.
I'd also like to preserve state following reconnects in an electron app (e.g. if the host gets suspended then resumed, socket.io gets disconnected).
I haven't tried this yet, but the following article discusses how to reuse socket id's across reconnects. I'll update if I have any success:
https://newbedev.com/reuse-socket-id-on-reconnect-socket-io-node-js

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.

nodejs socket.io : How to reconnect socker after socket.disconnect() is called?

How can I connect to socket again after I call disconnect
Here is the client source code
socket = io.connect('http://myServer:1339'); // connect socket
socket.disconnect(); // disconnect socket
socket = io.connect('http://myServer:1339'); // does not connect socket again !
Why do I call disconnect ?
Because I have myServer and myServer2 servers. If I switch between myserver and myserver2, I got many sockets connections (like adding)
Any idea on how to clearly close a socket and open a new one ?
Regards
You should not call io.connect a second time.
To reconnect, you should use
socket.socket.connect()

Socket.io fires connect event just after the second connect

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
});

Resources