HTML5 WebSocket API Overview
Majority of web applications use HTTP protocol to communicate with the server in order to display information on user browser. When browser loads a webpage, it sends HTTP request to the web server (IIS, Apache or Tomcat). The web server responds back with the information requested by the HTTP request. Each of these requests forces a web server to keep connection open for certain duration of time. As a result, we tax our web server with sometimes unnecessary requests. Moreover, HTTP request include lot of extra information which is not directly related to the request, such as header data.
We can see that HTTP is far from optimal if we want to have real-time communication open between browser – to server or between two browsers. In order to address these overheads and limitations, HTML5 introduced WebSocket API.
The HTML5 WebSocket was first introduced by Ian Hickson in the HTML5 specification document. However, it was later separated into its own specification and it is now exists as a separate an independent specification.
The HTML5 WebSocket establishes connection between a client and a server via WebSocket protocol. There is first initial handshake happen just like with HTTP in order to authenticate a client and a web server.
This handshake has the following characteristics
CLIENT -> SERVER: GET /demo HTTP/1.1 Host: mySite.com Connection: Upgrade Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 Sec-WebSocket-Protocol: sample Upgrade: WebSocket Sec-WebSocket-Key1: 4@1 46546xW%0l 1 5 Origin: http://www.mySite.com [8-byte security key] SERVER -> CLIENT: HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket Connection: Upgrade WebSocket-Origin: http:// www.mySite.com WebSocket-Location: ws:// www.mySite.com/dir WebSocket-Protocol: sample
After communication is established, the HTML5 WebSocket sends messages forth and back in a full-duplex mode. Messages are being marked at the beginning and end with the following bytes: 0x00 byte and 0xFF.