HTML5 WebSockets
HTML5 WebSockets
Contact Us
v s vetrivetri@hot
Message
Submit
HTML5 WebSockets
One of the most exiting new things in HTML5 is the ability to start pushing data from the server to the client. Traditionally web applications have depended on clients requesting data from the server. And this is fine in most applications. However there are lots of cases when you might want to push events to the client as soon as they happen and not wait for a client to query for them. For example a stock broker application requires traders to know about stock price changes as soon as they happen, alerting the trader 5 minutes after the fact is no good. Traditionally this could be done using long polling. This technique can be quite effective but a bit troublesome in getting to work reliably. The long polling mechanism has actually been formalized in the HTML5 specs as well with Server-sent DOM events and the the EventSource object. While quite effective, and relatively well supported, there is a newer technique of WebSockets that is far more capable.
foreach (var item in connections) { item.Send(s); } }; conn.OnClose = () => { connections.Remove(conn); }; conn.OnError = s => { }; });
Basically all we need to do is create a WebSocket object with the required URL and start listening for messages using the onmessage callback. Every time a message is received the eventArgs.data contain the actual message data being send. If we want to send data to the server we can also use the same WebSocket connection as this is fully duplex. All we need to to is use the send method specifying the data we want to send.
Messages
In the chat example all data being passed are just simple strings but this is no requirement. In fact if we want to send more complex data we can send it as binary data, no need to base64 encode it first.
Conclusion
I am exited about a lot of material in the new HTML5 standard but WebSockets and real time communication is extra exiting. it is going to enable a whole series of applications that where very hard, or even impossible, to write in a scalable way. And that is not just chat applications or tock trading but lots of others. The main problem right now is the lack of widespread support for the WebSocket standard. In fact only FireFox and Chrome have good support and IE is getting it in version 10. But fortunately libraries like SignalR make a lot of the same possible with fallbacks to more traditional communication mechanisms when WebSockets arent supported by the client and the server. Stay tuned for more on SignalR in a future post.
Enjoy!
2013 Digital Age Learning. All Rights Reserved | Terms of Use | Please Read our Privacy Policy