Sunday 20 October 2013

Introduction to Real Time Web

Wiki definition of Real Time Web is:

The real-time web is a set of technologies and practices that enable users to receive information as soon as it is published by its authors, rather than requiring that they or their software check a source periodically for updates.

The real-time web is really cool and all the massive social platforms like Facebook, Twitter and Google+ are using real-time web technologies for their instant notifications and interactive experiences. In this blog post I will give an introduction to two technologies that can be used to add real-time aspect to your web application: WebSockets and Server-Sent Events.
WebSocket
WebSocket is used to create persistent connection between the client and the server and both parties can use this connection to start sending and receiving data at any time. It is a protocol that provides full-duplex communication channels over a single TCP connection.
The connection you create using WebSocket is real time and is permanently open until you close it explicitly. When you open a socket, the server can push data to these connected sockets. WebSockets help to you achieve low latency. Since the socket is always open and listening, data will arrive to your browser as soon as data is pushed from the server.
WebSocket API is simple and easy to work with. This API contains methods for creating the connection, sending data, receiving data, and closing the socket. It also has an error handler and a state flag. This flag tells the client about the state of the socket whether it is connecting, open, closing, or closed.
This is how you can create a new WebSocket:
var socket = new WebSocket('ws://theserver.com/mynews:8080');
Now send some data to the server when it is opened:
socket.onopen = function () {
  socket.send('Hello Server'); 
};
Receive data from the server:
socket.onmessage = function (e) {
  console.log('Server: ' + e.data);
};
Logging error:
socket.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};
Server-Sent Events
Sometimes you need simple push-based data from the server. Server-Sent Events are just for this. This enables one-way information flow from your server to the browser. EventSource object is used to manage Server-Sent Events. The browser immediately tries to establish a connection when you create a EventSource object, passing it a URL to connect to.
var es = new EventSource('/mydata');
Now setup handler for message, open and error event:
es.addEventListener('message', function(e) {
  console.log(e.data);
}, false);

es.addEventListener('open', function(e) {
  // Connection was opened.
}, false);

es.addEventListener('error', function(e) {
  if (e.readyState == EventSource.CLOSED) {
    // Connection was closed.
  }
}, false);
Use cases for Server-Sent Events are: Sending notification to browser, social media feed updating, live price updating, stock ticker streaming etc.

No comments:

Post a Comment