Pergunta

I'm trying to understand how web sockets work. I do have basic understanding that unlike AJAX in web sockets connection is always open which is convenient for real time applications.

This is very basic example using socks:

   var sock = new SockJS('http://mydomain.com/my_prefix');

   sock.onopen = function() {
       console.log('open');
   };

   sock.send("request to send (JSON)");

   sock.onmessage = function(e) {
       console.log('message', e.data);
   };

   sock.onclose = function() {
       console.log('close');
   };

Requirement: I have multiple widgets to display real time data so I want each widget to subscribe to a JSON request/service, keep connection open and unsubscribe whenever required.

Question: In this case how do we handle multiple requests, like we do with typical AJAX setup?

I'll appreciate if someone can guide me to correct direction, give me an example or a link to tutorial.

Anyone?

Foi útil?

Solução

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:

Implementing events in my own object

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top