Introduction to Websocket
The WebSocket specification is a new feature of HTML5. It defines a full-duplex single socket connection over which messages can be sent between client and server. The WebSocket standard simplifies much of the complexity around bi-directional web communication and connection management. The Websocket standard reduces polling and the unnecessary network throughput overhead.
Image courtesy of Kaazing
We can see on this figure the reduction in latency. Once the connection is established, messages can flow from the server to the browser. As the connection remains open, there is no need to send another request to the server. If you want to see some other comparisons, just click on the image above or visit WebSocket.org
The Websocket protocol
To establish a WebSocket connection, the client and server upgrade from the HTTP protocol to the WebSocket protocol during their initial handshake. There are several handshake mechanisms. I will just present the basic handshake of one of them in this article (the websocket protocol 76). It's the one which is implemented in mbed websocket library. For more information, please refer to: protocol-76.
The handshake from the client looks as follows:
GET /demo HTTP/1.1 Host: example.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://example.com ^n:ds[4U
The handshake from the server looks as follows:
HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Origin: http://example.com Sec-WebSocket-Location: ws://example.com/demo Sec-WebSocket-Protocol: sample 8jKS'y:G*Co,Wxa-
Once the Websocket connection is established, data can be exchanged according to this format:
- Send a 0x00 byte
- Encode the message using UTF-8 and send the resulting byte stream
- Send a 0xFF byte
Websocket on Mbed
There is here a simple websocket client which must be used with a wifi module (Wifly RN131-C). This library has been used for the Internet of Things project.
14 comments on Websocket:
Please log in to post comments.