WebSocket protocol is a TCP-based network protocol designed to be a two-way link between a web application and a web server in client server model. We have talked about the Protocols related to Internet of Things, this Protocol; standardized by the IETF as RFC 6455 in 2011 and as WebSocket API in Web IDL by W3C, can be a part of IoT related protocols. Normally, we can use WebSocket Protocol for live graphs, as an example.
What is WebSocket Protocol?
In a pure HTTP connection every action of the server requires a previous request from the client, it is enough for WebSocket protocol when the client opens the connection. The server can then use this open connection actively and can deliver new information to the client without waiting for a new connection from the client.
A server-initiated transmission is in a pure HTTP connection only by delayed responses to a client-initiated request (long polling). Technically in WebSocket, like HTTP, the client sends a request with the difference that after the transfer of the data to connect the underlying TCP connection remains open and allows transfers in both directions.
---
A secure version of the WebSocket protocol is implemented in Firefox, Safari, Google Chrome, Opera and Internet Explorer 10, mobile version of Safari and BlackBerry Browser.
Example of WebSocket Protocol
Client request:
1 2 3 4 5 6 7 8 | GET /chat HTTP/1.1 Host: jima.in Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Origin: http://jima.in |
Server response:
1 2 3 4 5 | HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat |
The introduction of WebSocket makes it possible for web apps to handle near real-time data without resorting to long-polling.
Nginx and WebSocket Protocol
Socket.IO is a WebSocket API for Node.js application. Racket.IO is for PHP application. Example basic configuration for Nginx :
1 2 3 4 5 6 | location /wsapp/ { proxy_pass http://wsbackend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } |
This is the basics of real time web application as well. This is a typical cURL format with flags to get the response :
1 | curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: echo.websocket.org" -H "Origin: http://www.websocket.org" http://echo.websocket.org |