Willem van Gerven Willem van Gerven - 1 month ago 9
Node.js Question

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

Answer

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.

Comments