Web Sockets

7/27/2011

Web sockets are two-way (i.e. full duplex), real-time, TCP connections between browser and server. Unlike most AJAX implemenations, Web Sockets can connect across domains. WebSockets are kept open, so have low latency compared to XMLHttpRequest. The amount of data sent is also typically far less (binary rather than XML, no headers, routing, auth or lead-in required as the connection is already open).

The API

·         var ws = new WebSocket(‘ws://myServer.com/whatever[:optionalPort]’);

·         ws.onopen = function(e) { alert("Opened"); };

·         ws.onmessage = function(e) { alert(e.data); };

·         ws.onclose = function(e) { alert("Closed”); };

·         alert(ws.URL);

·         alert(ws.readyState);       // 0=connecting, 1=open, 2=close

·         alert(ws.bufferedAmount);

·         ws.send(stringData);

·         ws.close();

 

The URL

·         Only supports the protocols:

o    ws

o    wss (secure web-sockets)

The Handshake

Opening a web-socket actually starts with a HTTP connection. Negotiation occurs (we included to magic headers: "Upgrade:WebSocket" & "Connection:Upgrade") and (if successful) the connection is upgraded to a web-socket.

The Client-Side Sample

    ws = new WebSocket("ws://myServer:myPort/someUrl");
    ws.onopen = function(e) {Console.WriteLine("Connection opened.");}
    ws.onmessage = function(e) {Console.WriteLine("Server says: " + e.data);};
    ws.onclose = function(e) {Console.WriteLine("Connection closed.");};
    ws.send("Hello Server! Can you hear me?");