Sunday, May 3, 2015

WebSockets, SignalR and Real Time web applications

WebSockets changed the way we can communicate in our web apps between the client and server. Previously we could keep http 1.1 persistent connection between client and server, but it was used only for the client to keep the connection open for making another request to get any updates.

The TCP protocol used by websockets now allows the server to communicate to the clients without the clients initiating a request! In short, it allows for bi-directional full-duplex communication between the client and the web server.

That means these messages can be transmitted between client and server concurrently. And the messages don't rely on any rigid specfications like headers and cookies, which means it can be very lightweight and very fast!


The WebSockets API looks very simple

var socket = new WebSocket("ws://echo.websockets.org");

//Once connection opens, send message to server
socket.send("hello from websockets!");

//To receive messages from the server, subscribe to an onmessage event
socket.onmessage( function(event){
            alert("I got server data! " + event.data);
});

But to work at this low level, you still have to worry about serializing data to send to the server and deserializing data from the server, managing connections, supportability in browsers, ordering of messages etc. The answer - SignalR!

SignalR is just an encapsulation wrapper around WebSockets so we no longer need to use long polling Javascript methods to get instant updates from the Server. This opens up a slew of opportunities for developing all kinds of real time web applications.

Learning demo on GitHub:
https://github.com/yashish/RealTime-PerfMon-using-SignalR-Knockout.git

No comments:

Post a Comment