Socket io emit function making new connection every time - node.js

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.

Related

IORedis or (node_redis) callback not firing after calling custom Redis commands/modules

When using redis client (ioredis or node_redis) inside websocket's message event in a nodejs app, the callback for any command is not immediately fired. (the operation does take place on redis server though)
What is strange is that the callback for the first command will fire after i sent a second message, and the callback for the second will fire after i send a third.
wss.on('connection', (socket, request) => {
socket.on('message', (data) => {
console.log("will send test command")
this.pubClient.hset("test10", "f1","v1", (err,value) => {
//callback not firing first time
console.log("test command reply received")
})
})
}
the redis command is working as expected though in other parts of the app and even when inside the on connection directly like below.
wss.on('connection', (socket, request) => {
console.log("will send test command")
this.pubClient.hset("test10", "f1","v1", (err,value) => {
//callback fires
console.log("test command reply received")
})
socket.on('message', (data) => {})
}
UPDATE:
I had this all wrong. The reason for the weird callback behavior is the result of one my custom Redis modules not returning a reply.
And this seems to have caused all callbacks after this call to seem to have some kind of a one step delay.
I had this all wrong. The reason for the weird callback behavior is the result of one my custom Redis modules not returning a reply. And this seems to have caused all callbacks after this call to seem to have some kind of a one step delay.

How to use Promise with redux and socket.io

I am a newbie to react-redux. I am stuck at situation wherein i emit an action to the server. The server in turn makes a third party API request which return a promise. My server.js file for handling socket connection in the server looks like the following
import Server from 'socket.io';
export default function startServer(store) {
const io = new Server().attach(8090);
store.subscribe(
() =>io.emit('curr_news', store.getState().toJS()));
io.on('connection', (socket) => {
socket.emit('curr_news', store.getState().toJS());
socket.on('action', store.dispatch.bind(store));
});
}
As you can see the action is what the client emits and the server makes an appropriate request when it receives the necessary action after which it emits the current state. The following is a sample reducer file
export default function reducer(curr_feeds = CURRENT_FEEDS, action) {
switch (action.type) {
case 'GET_TEST1DATA':
return getTest1data(curr_feeds);
case 'GET_TEST2DATA':
return getTest2data(curr_feeds);
}
}
here getTest1data and getTest2data essentially return a promise as it makes a request to some third part API. My problem is that as the the socket emits the curr_news immediately due to which the value of store.getState() is undefined.
My question is how do I make the store to observe and emit the socket once the promise resolves and not before that? Thanks for the help in advance.
When you subscribe to the store you gain a state whenever it updates. If that new state is a promise, you could process that:
Store.subscribe(state => state.then(promisedData => io.emit(promisedData))

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

socket.io data seems to be sent multiple times(nodejs and craftyjs)

I am following this tutorial on making HTML5 games. I wanted to try and mix node in to make it multiplayer. I am using node.js(v0.10.4) on server and crafty.js on front end.
I am using socket.io to send and receive messages. For now it's just me(not multiple clients). The weird thing that happens is that the message that comes from the server seems to be sent multiple times. I turned on debug mode in socket.io but it only seems to be sending the data once, yet on the front end the data seems to be coming in, in multiples. I set an incrementor on the data and it seems as if the incrementor is not incrementing multiple times but instead I am getting multiple copies of the same data.
here's node code:
var http = require('http').createServer(handler),
static = require('node-static'),
io = require('socket.io').listen(http);
io.set('log level', 3);
http.listen(80);
//attach the socket to our server
var file = new static.Server(); //Create a file object so we can server the files in the correct folder
function handler(req, res) {
req.addListener('end', function() {
file.serve(req, res);
}).resume();
}
io.sockets.on('connection', function (socket) { //listen for any sockets that will come from the client
socket.on('collected', function(data) {
/**** here's where the data is being sent back to the client *****/
socket.emit('messageFromServer', { data: data.number });
});
});
and here's front end code:
//messenger entity
Crafty.c('SendRecieveMessages',{
count: 0,
sendMessageToServer : function() {
console.log('got a village');
/**** Here's where we send the message to the server ****/
socket.emit('collected', { village : "The message went to the server and back. it's collected", number : this.count });
this.count++;
},
recieveMessageFromServer : function() {
socket.on('messageFromServer', function(data) {
/*** This data seems to be coming back or logging multiple times? ***/
console.log(data);
});
}
});
Lastly here's a screenshot of the debug in process. As you can see number is not always incrementing, it almost looks like the data is getting stored. Thanks!
http://cl.ly/image/0i3H0q2P1X0S
It looks like every time you call Crafty.c, recieveMessageFromServer() is getting called too. Every time recieveMessageFromServer is invoked, it attaches an additional event listener on the socket. That's why the first time data comes back you get one copy, then the second time you get two, the third time you get three, and so on.
You either need to prevent recieveMessageFromServer from being called multiple times, or use removeListener or removeAllListeners to remove the previously attached listeners.
Thanks to #Bret Copeland for helping me figure this one out. As he pointed out, every time socket.on() is called, it seems to add another listener. To prevent this...
I declared a global variable:
I declared a variable as a property in my Game object(in craftyjs, so use whatever you want in your setup)
Game = {
//lots of other code here...
//need this to use later for socket.io
send_message : true
}
then edited my recieveMessageFromServer() function to check whether its ok to send the message or not:
recieveMessageFromServer : function() {
console.log('does this show up multiple times?');
/* Check whether the send_message is true before sending */
if (Game.send_message) {
socket.on('messageFromServer', function(data) {
console.log(data);
Game.send_message = false;
});
}
}

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