javascript - Web sockets multiple requests -


i'm trying understand how web sockets work. have basic understanding unlike ajax in web sockets connection open convenient real time applications.

this basic example using socks:

   var sock = new sockjs('http://mydomain.com/my_prefix');     sock.onopen = function() {        console.log('open');    };     sock.send("request send (json)");     sock.onmessage = function(e) {        console.log('message', e.data);    };     sock.onclose = function() {        console.log('close');    }; 

requirement: have multiple widgets display real time data want each widget subscribe json request/service, keep connection open , unsubscribe whenever required.

question: in case how handle multiple requests, typical ajax setup?

i'll appreciate if can guide me correct direction, give me example or link tutorial.

anyone?

the thing http when send multiple requests, reqa, reqb, reqc, server has response these requests in same order resa, resb, resc (this under assumption keep-alive on, see the specification). browser knows response request.

but websockets have write code manually. there other options well. example 1 of interesting idea use event system. server accept json data in form

{   "event": "test",   "data": ["foo"] } 

and send data client in same form. in situation can this:

var eventmanager = // code here; sock.onmessage = function(e) {   var msg = json.parse(e.data);   eventmanager.trigger(msg.event, msg.data); }; 

and can register events doing

eventmanager.on("test", function(data) {   // handle "test" event here }); 

of course have implement eventmanager. can use 1 of existing implementations, backbone.js or can implement on own, here:

implementing events in own object


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Socket.connect doesn't throw exception in Android -

iphone - How do I keep MDScrollView from truncating my row headers and making my cells look bad? -