WebSocket SaaS | WebSocket Protocol Handshake

There are many technologies that the server will send data to the client at the very moment it knows that the new data is available such as push, comet, etc. These all create an illusion that the server initiated the connection called long polling. With the long polling, the client opens an HTTP connection to the server and keeps it open until it receives a response. These techniques work quite well, we use them daily in applications such as Gtalk.

All of these work-around have one problem such as they carry the overhead of HTTP and will not be suited for low-latency applications.

WebSocket: Sockets into the web

The WebSocket defines an API establishing a socket connection between a browser and a server. Simply, it is a persistent connection between the client and the server and both parties can send data at any time. It is an independent TCP-based protocol. Its only relationship to HTTP is that the handshake is handled using HTTP servers as an Upgrade request.

WebSocket protocol handshake

For establishing a WebSocket connection, the client sends a handshake request and the server sends back the handshake response as shown below.

GET /chat HTTP/1.1
Host: inapp.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://old.inapp.com

Server response

HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

websocket

Getting started

Create a WebSocket connection using javascript (supports only in modern HTML 5-enabled browsers).

var connection = new WebSocket(‘ws://localhost:8080/test’);

You might have noticed that ws:// which is the URL schema for websocket connection. There is also wss:// for a secure WebSocket connection.

// When the connection is open, send some data to the server
connection.onopen = function () {
connection.send(‘Ping’); // Send the message ‘Ping’ to the server
};

// Log errors
connection.onerror = function (error) {
console.log(‘WebSocket Error ‘ + error);
};

// Log messages from the server
connection.onmessage = function (e) {
console.log(‘Server: ‘ + e.data);
};

The Server-Side

With the release of Windows Server 2012 and Windows 8, Internet Information Services (IIS) 8.0 has added support for the WebSocket Protocol.

http://www.iis.net/learn/get-started/whats-new-in-iis-8/iis-80-websocket-protocol-support

The apache-WebSocket module is an Apache 2.x server module that may be used to process requests using the WebSocket protocol (RFC 6455) by an Apache 2.x server.

https://github.com/disconnect/apache-websocket

Also, Tomcat 7 provides API for WebSocket but has not yet been finalized.

http://tomcat.apache.org/tomcat-7.0-doc/web-socket-howto.html

Have questions? Contact the technology experts at InApp to learn more.