WebSocket in HTML5

HTML5 provides a new thing called a WebSocket. Now data can flow between the browser and server without having to send HTTP headers until the connection is broken down again. Welcome to the world of PUSH technology!

What is Websocket?
WebSocket is bi-directional (full-duplex) communication channel over a single TCP (Transmission Control Protocol) socket for client or server application... goes too much technical, ok then
WebSockets opens a connection to a server and the connection stays open until you decide to close it. From there, you can start sending messages from the browser to the server and you can define a callback function for when the server send data back. Basically we got rid of each time new request for server.

How it Works?
As same as common socket phenomena, the client first connects to a server, the sever adds the new id to a list of connected ids and the browser sends the message to the server. The clients (there could be thousand) don’t have to query frequently to find out if there are new messages or not, both the browser and the server only communicate when they needed. When there is no need of connection the connection will be closed.

How The JS Code look like?
socket= new WebSocket('ws://');
socket.onopen= function() {
    socket.send('hello gaurav');
socket.onmessage= function(s) {
    alert('gaurav says: '+s);
Note: You will need a specialized socket application on the server-side (phpwebsocket) to take the connections and do something with them. You can also take a look at Gimite's web-socket-js it is HTML5 Web Socket implementation powered by Flash.

At the moment, it’s still being standardized by the W3C; however, the latest versions of Chrome and Safari have support for WebSockets.  

Post a Comment