tony590
tony590

Reputation: 145

WebSocket best practice

I'm playing with Websockets and I have ended with a quite few socket.on(msg, function()) events. So I'm wondering what is the best practice, just keep adding socket.on events for each case or use just one event with sub-events that will be handled in a

switch(json.type) {
       case 'maps' : add_maps_from_json(json);
                    break; 
       case 'fList': show_floor_list(json); 
                    break; 
       ...
       case 'xxx':

Upvotes: 4

Views: 3831

Answers (2)

gzost
gzost

Reputation: 2445

Since there is a single 'onmessage' event fired, it would seem cleanest to have a single handler for this. Otherwise things can get messy very quickly, since there is no central place where it's apparent what happens once the event fires.

Additionally, with a multitude of handlers, that's potentially a lot of code which all gets called on each message. This may be uncritical for a lot of use cases, but with high message frequencies and/or time-critical handling, having a single function seems the more efficient solution.

Incidentially, a single handler function is what Mozilla has in its WebSocket tutorial

Upvotes: 3

Kurt Pattyn
Kurt Pattyn

Reputation: 2798

Both approaches can work.
However, if you use one event, then you can do some common pre- or post processing on the message. Doing this in separate socket.on events, would force you to duplicate the code (even if the pre-/postprocessing is done in a separate method).
So, I would go for the one socket.on approach.

Upvotes: 1

Related Questions