Table of Contents
Introduction to Websockets¶
The WebSocket specification is a new feature of HTML5. It defines a full-duplex single socket connection over which messages can be sent bi-directionally 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 as was previously the standard. This massively simplifies what before required complex workarounds involving having the client polling 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, but I will just present one of the basic handshakes here(the webSocket protocol 76). It's the one which we have implemented in the mbed websocket library here. For more information, please refer to: protocol-76.
The handshake from the client is 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 response from the server:
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¶
We have here, a simple WebSocket-client library which can be used with a Roving Networks WiFi module (WiFly RN131), or an Ethernet connection. This library has been used in the Internet of Things project.
1 related question:
3 months, 3 weeks ago