Julian H. Lam
Julian H. Lam

Reputation: 26124

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

Let's say I have a socket server that is listening on a generic message, and only alters its behaviour due to different payloads. For example:

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 socket emits are made with the users.get message, how would I be able to distinguish between their returns on the client side, assuming both are made in the same page?

The immediate solution would be to merge the two calls together, but if that situation were impossible, how would I manage it otherwise? In this particular instance, one users.get call is made in the header of the page on page load, and another users.get is made from inside the page content.

Knowing full well that one call is in the header, and another is in the content means that it might work if on the client-side, .once() is used instead of .on(), but that still involves a race condition, so I was wondering if there were any standard way of dealing with this.

Upvotes: 4

Views: 498

Answers (1)

Nitzan Shaked
Nitzan Shaked

Reputation: 13598

A given instance of socket (the thing you call .on on) equals a connection, which in turn equals a specific client. If 2 clients make a similar emit it will arrive on 2 different sockets, and your handler can you the socket instance to return the response to the specific client.

If the same socket makes 2 emits, then that's a client-server app-level protocol issue, and should be handled in the client and in the server. Maybe it means there's no really no difference (to your app) between the requests, so it doesn't matter which responses arrives 'first'. If there is a difference, then maybe add a "request id" field to the request, and echo that field in the response, allowing the client to associate each response with the original request that triggered it.

Upvotes: 1

Related Questions