Get connection status on Socket.io client - node.js

I'm using Socket.io, and I'd like to know the status of connection to the server from the client-side.
Something like this:
socket.status // return true if connected, false otherwise
I need this information to give a visual feedback to the user if the connection has dropped or it has disconnected for any reason.

You can check the socket.connected property:
var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
console.log('check 2', socket.connected);
});
It's updated dynamically, if the connection is lost it'll be set to false until the client picks up the connection again. So easy to check for with setInterval or something like that.
Another solution would be to catch disconnect events and track the status yourself.

You can check whether the connection was lost or not by using this function:-
var socket = io( /**connection**/ );
socket.on('disconnect', function(){
//Your Code Here
});
Hope it will help you.

These days, socket.on('connect', ...) is not working for me.
I use the below code to check at 1st connecting.
if (socket.connected)
console.log('socket.io is connected.')
and use this code when reconnected.
socket.on('reconnect', ()=>{
//Your Code Here
});

Track the state of the connection yourself. With a boolean. Set it to false at declaration. Use the various events (connect, disconnect, reconnect, etc.) to reassign the current boolean value. Note: Using undocumented API features (e.g., socket.connected), is not a good idea; the feature could get removed in a subsequent version without the removal being mentioned.

#robertklep's answer to check socket.connected is correct except for reconnect event, https://socket.io/docs/client-api/#event-reconnect
As the document said it is "Fired upon a successful reconnection." but when you check socket.connected then it is false.
Not sure it is a bug or intentional.

Related

Attaching event emitter to socket.connected

I am currently writing an Electron app, for which in the main process I want to talk to a server over websockets.
Part of my main process' code base depends on the user's socket connection status. I require the socket.io-client library
const socket = require('socket.io-client')(host);
which gives me access to the variable socket.connected, which is true or false according to whether a connection is established to the server.
Thus, what I would like is to attach an event emitter to this variable. I have made it to work with polling
var events = require('events').EventEmitter;
var event = new events();
// Emits successfully every 200ms 'Connection: true|false'
event.on('status', function(status){
console.log('Connection: ', status);
});
setInterval(function() {
let status = socket.connected;
event.emit('status', status);
}, 200);
but was wondering whether this truly is the way to implement it. To me it seems strange to have to resort to polling in an async framework like nodejs. On the other, I could not find other ways to implement. Best-case scenario would be to attach somehow an event emitter directly to socket.connected, but was unable to find how to do that. Could anybody advise me on a better way to implement?
Thanks
You can get notified of the completion of a client connection with the connect event:
socket.on('connect', function() {
// client socket is now connected to the server
});
socket.on('disconnect', function() {
// client socket is now disconnected from the server
});
Documentation for client events here: http://socket.io/docs/client-api/#manager(url:string,-opts:object). There are other events in that doc if you also want to see other things like a reconnect.

How to change status of perticular user when socket is disconnect?

II am here to resolve my problem in socket connection and disconnection. I want something like this
1. connection done. (ok) // working
2. on perticular event I am doing to update location of user in database { Here user is online }.
3. But somehow network disconnection the socket will be disconnect and user must be offline. this can be using disconnect event. but I am not aware how to recognise that perticular user has to be updated offline because I don't have user_id in `socket.on('disconnect')` event. please help me out. I googled it everywhere but not helped me out.
sorry for wanting logic but it is really needed to me.
Thanks in advance. :)
On disconnect, like you mentioned, you can track the id based on this.id or socket.id.
socket.on('disconnect', function() {
console.log(this.id);
console.log(socket.id);
});
Alternatively, you can handle sockets by using a global array, as suggested in this answer.
If netiher of those are suitable, you can do some dependency injection on the socket object
io.on('connection', function(socket) {
//Obtain the user_id somehow and add it into the socket object
socket.user_id = "hello_world";
socket.on('disconnect', function() {
console.log(socket.user_id);
});
});

Socket.IO: connection to a non-existing namespace

First post, i'll try to be as clear as possible :)
I'm trying to create on Demand namespaces on my SocketIO/NodeJS App.
Basically, the server create a specific namespace for each client.
I need to handle, server side, the case where the client try accessing a non-existing namespace.
The idea is to avoid any unwanted connection server-side, or at least, handle it to force the disconnection.
But while testing, it seems that when i try this, on client Side :
var socket = io("thisNameSpaceDontExist");
socket.on('connect', function(){
window.console.log('connected to server');
})
The 'connect' event won't trigger, which seems perfect !
Doing a console.log on socket, it displays this:
connected: false
disconnected: true
But the main problem, is that, Server Side, it's different, there is an active connection...
While doing some research, i found this issue https://github.com/Automattic/socket.io/issues/1867, still, i'm on the last version at this time: 1.3.5
for information, the socketIOHandler code i'm using:
io.on('connection', function (socket) {
console.log("[SocketIOHandler::Connection] +1");
socket.on('disconnect', function () {
console.log("[SocketIOHandler::Disconnection] -1");
});
});
PS:
Also find some issues and MR claiming the support of dynamic namespaces: https://github.com/Automattic/socket.io/issues/1854, but these are not merged, so i don't really understand the behavior on my code...
Thank you!

Socket.io : what happen to the client(socket) after a user is disconnected? Can I/Should I remove it?

I am using socket.io, and I want to know how can I remove the client(socket) after a connection is closed. (In fact, I don't know what is going on after a connection is close, will that socket remained there? Should I remove it? Will it take up memory?)
My code:
socket.No = socketNo++;
io.sockets.on("connection",function(socket){
setInterval(function(){
console.log("Server calling update collection with socket No.",socket.No);
},3000);
//When connection is close()
socket.on("disconnect",function(){
console.log("A user disconnected");
});
})
What happen is that, for example, I disconnect from the server, I find that server is still logging. What can I do so that I can stop it?
Thanks~
In the code above, it is setInterval that is causing the additional logging.
You will need to store off the id returned from setInterval then clear it using clearInterval on a disconnect event.
Something like:
io.sockets.on("connection",function(socket){
var intervalId = setInterval(function(){
console.log("Server calling update collection with socket No.",socket.No);
},3000);
//When connection is close()
socket.on("disconnect",function(){
console.log("A user disconnected");
clearInterval(intervalId);
});
})
Other than that, no need to do anything else with the socket on the server side. It will get garbage collected at some point.

socket.io - works first time, not second time onwards

When I start my node.js server and client gets connected, I am able to send a request from client (socket.emit) and get a response (socket.on('rentsAround'....)). But when I connect 2nd time onwards, the client is able to send, but server can not send or emit. So I have to restart the server again. I understand that it is working as expected, but somehow my understanding is wrong somewhere... Would someone please point out.
client side:
========
var socket = new io.Socket();
socket = io.connect();
socket.on('rentsAround', function(data){
registration.handleRentsAround(data);
});
socket.on('locationDetailsRes', function(data){
registration.handleRentsAround(data);
});
socket.on('connect', function(data){
alert('inside connect on client side');
});
socket.on('disconnect', function(){
// do something, if you want to.
});
.............
socket.emit("searchRent", {"lat":lat, "lng":lng});
server side:
========
socket.sockets.on('connection', function(client){
client.on('searchRent', function(msg){
console.log('inside on connection');
// do something and reply back
client.emit('rentsAround',{"totalRents":docs.length, "rents":docs});
});
client.on('disconnect', function(){
sys.puts("client disconnect");
mongoose.disconnect();
});
Socket.io 0.7 onwards will try and reuse connections to the same host. In my experience I've found this behaviour can be a little flakey.
I can't tell from the small code sample you provided, but I suspect the problem is that the second call to connect() is trying to reuse the first (closed) connection.
The workaround is to pass the 'force new connection' option when you call connect(). Eg:
io.connect("http://localhost", {'force new connection': true});
Your second line discards the object created in the first line. Simply doing this should work:
var socket = io.connect();
The problem with first send and second fail could be due to browser/protocol. I have seen such behaviour with Internet Explorer and XHR transport, and also with Opera using JSONP.
If you are using IE, try switching to JSONP and it should work properly. This can be done on the server side, by supplying the transport list to configuration. Just make sure JSONP comes before XHR. Something like this:
sio.set('transports', [
'websocket'
, 'flashsocket'
, 'jsonp-polling'
, 'xhr-polling'
, 'htmlfile'
]);
As of socket.io 1.0, two settings control this behaviour:
"force new connection":true, on the client connect() call.
"cookie":false, on the server Server() constructor.
Apparently, both produce the exact same behaviour.
The second method is, as of today, undocumented. However, looking at the source code you can see that all options passed to socket.io Server() are passed to the internal Engine.io library Server() constructor, which lets you change any of the options there. These options are documented here:
https://github.com/LearnBoost/engine.io

Resources