The thing is that with HTTP when you send multiple requests, say reqA
, reqB
, reqC
, then the server has to response to these requests in the same order resA
, resB
, resC
(this is under assumption that keep-alive
is on, see the specification). The browser then knows which response is to which request.
But with WebSockets you have to write this code manually. There are other options as well. For example one of the interesting idea is to use event system. The server will accept JSON data in the form
{
"event": "test",
"data": ["foo"]
}
and it will send data to client in the same form. In this situation you can do something like this:
var EventManager = // some code here;
sock.onmessage = function(e) {
var msg = JSON.parse(e.data);
EventManager.trigger(msg.event, msg.data);
};
and you can register to events simply by doing
EventManager.on("test", function(data) {
// handle "test" event here
});
Of course you have to implement EventManager
. For that you can use one of the existing implementations, like Backbone.js or you can implement it on your own, like here: