Capture connection events of two socket servers - node.js

I know I am overthinking this... but the answer is just not clicking.
I have two servers, one a TCP socket server and the other a SockJS server. I need to combine both of their connection events into one super event:
async.parallel({
tcp: function (done) {
self._tcp = net.createServer(function (sock) {
done(null, sock);
});
},
ws: function (done) {
self._ws = sockjs.createServer(function (sock) {
done(null, sock);
});
}
}, function (err, results) {
// This never gets fired!!!
// But I'd like to do stuff here with both
// socket instances – you know, like piping =)
});
Originally I had the TCP connection nested within the WS connection, but that's proving to be problematic as it requires a rigid connection sequence. What I really need is an event that is fired when both connections have been established and have access to their respective sock instances. Help jogging the brain would be much appreciated!

This might be overly simple - but looking at the sockjs documentation, there isn't a callback function for createServer() - so it's never going to loop back through the callback of your parallel function.
Try just calling done(null, sock); right after you do socket.createServer(); and you should be all set.
Doc: https://github.com/sockjs/sockjs-node

Related

Socket io emit function making new connection every time

I want to made one connection on one emit function at a time in socket io with react and node js, but it is making new connection every time when emit is called from frontend. Is there any solution for this?
Reactjs code:
socket.emit('getMessages', 1000,this.state.userData._id,id);
Nodejs Code:
client.on('getMessages', (interval,sID,rID) => {
try {
//get messages from mongodb
} catch (err) {
console.log(err);
}
client.on('disconnect', () => {
console.log(`Socket ${client.id} disconnected.`);
});
});
I want to get message IDs but every time I am sending new IDs it makes a new connection and sending previous messages as well.
If you want something to only happen once you could use client.once(....).
If you want the server to not listen for the event anymore after it was emitted once you could add client.removeListener('getMessages') at the end of your listener.
Hope this is helpful. Not sure what behaviour your looking for exactly though.

remoteDisconnect socket.io and redis

I'm trying to implement socket.io with Redis adapter in NodeJs.
Mostly it works, but sometimes I am still getting errors when trying to disconnect / connect sockets, so I think I haven't implement it correctly.
Could someone please explain what is the difference between
socket.disconnect(); and io.of('/').adapter.remoteDisconnect();
If I initialise my io with:
io.adapter(redisIO({
host: config.server.redis.host,
port: config.server.redis.port,
requestsTimeout: config.server.redis.request_timeout
}));
Shouldn't then socket.disconnect(); be aware of using redisIO? If using remoteDisconnect can I still capture socket.on('disconnect', fn) or should remoteDisconnect be called in socket.on('disconnect', fn)?
What happens if client disconnects? How can I propagate it to socket.io cluster?
Any working examples will be appreciated :)
Thanks!
Capture the socket event disconnecting, not disconnect, by then it's too late!
socket.on('disconnecting', () => {
var room_name = sess.id
io.of('/').adapter.remoteDisconnect(room_name, true, err => {
delete socket.rooms[room_name]
socket.removeAllListeners()
})
})

In socket.io, how do I differentiate between 2 triggers of the same event?

Suppose I have a simple event defined as
socket.on('event', function(data){
...
});
And if the client fires it two times, one after another
socket.emit('event'); //once
socket.emit('event'); //again
Is there a way to *inherently** differentiate between the two events?
*I don't want want to depend on data because that's just a client side variable, and could easily be tampered with. (right?)
For context, it's related to this question.
I would use sessionSockets to save data for each user on the server side.
sessionSockets.on('connection', function (err, socket, session) {
socket.on('event', function() {
if(!session.eventReceived) {
// manage event
// save event received in session
session.eventReceived = true;
session.save();
}
});
});

What's the difference between req.setTimeout & socket.setTimeout?

I have two options to set a timeout to my http request. I am not sure about their difference.
First one is:
req.setTimeout(2000,function () {
req.abort();
console.log("timeout");
self.emit('pass',message);
});
Second one is:
req.on('socket', function (socket) {
socket.setTimeout(2000);
socket.on('timeout', function() {
req.abort();
self.emit('pass',message);
});
}
socket.setTimeout sets the timeout for the socket, e.g. to implement HTTP Keep-Alive.
request.setTimeout does internally call socket.setTimeout, as soon as a socket has been assigned to the request and has been connected. This is described in the documentation.
Hence, it's no difference, and you can choose which way to go. Of course, if you already have a request in your hands, you'd stick to the request's setTimeout function instead of digging for the underlying socket.

How can I detect, when the connection of the client gets interrupted in socket.io?

I have a Node.js-Server with a socket.io-connection to a browser-client. sometimes the connection gets interrupted, for example, when I need to restart the server. When that happens, how can the client know this?
Here's an example on how you can achieve that on the client side:
var chat = io.connect('http://localhost:4000/chat');
chat.on('connect', function () {
console.log('Connected to the chat!');
});
chat.on('disconnect', function () {
console.log('Disconnected from the chat!');
});
As you can see, you keep the connection variable and you use connection_variable.on('disconnect', callback_function_here)

Resources