How do you distinguish socket.io calls when their messages are the same?

Let's say I have a socket server that listens for a general message and only changes its behavior due to different payloads. For instance:

 socket.on('users.get', function(payload) { // retrieve user data // return data that corresponds to the data requested in "payload" socket.emit('users.get', returnData); }); 

If two emit sockets emit made with the message users.get , how could I distinguish between their return on the client side, assuming they are both made on the same page?

The immediate solution would be to combine the two challenges together, but if such a situation were impossible, how could I manage it otherwise? In this particular case, one call to users.get is made in the page header when the page loads, and another users.get is made from the contents of the page.

Knowing that one call is in the header and the other in the content means that it can work if .once() instead of .on() on the client side, but this is still related to the race status, so I was wondering is there any standard way to handle this.

+4
source share
1 answer

A given instance of socket (what you call .on on) is equal to a connection, which in turn is equal to a specific client. If 2 clients make a similar emit , it will go to 2 different sockets, and your handler will be able to give you a socket instance to return a response to a specific client.

If the same socket makes 2 emissions, then the problem is with the client-server application-level protocol and should be handled both on the client and on the server. Perhaps this means that there is no difference between the requests (to your application), so it doesn’t matter which responses come first. If there is a difference, then perhaps add the "request id" field to the request and repeat this field in the response so that the client can associate each response with the original request that caused it.

+1
source

Source: https://habr.com/ru/post/1479069/


All Articles