The WebSocket protocol is used to work with the existing network infrastructure. As part of this design principle, the Protocol Specification for WebSocket connection defines starting its life as an HTTP connection, ensuring full backward compatibility with the pre-WebSocket world. Switching from HTTP to WebSocket is called WebSocket handshake.
The browser sends a request to the server, which indicates that it wants to switch from the HTTP WebSocket protocol. The client expresses its wish by upgrading the title:
GET ws://echo.websocket.org/?encoding=text HTTP/1.1Origin: http://websocket.org Cookie: __utma=99as Connection: UpgradeHost: echo.websocket.orgSec-WebSocket-Key: uRovscZjNol/umbTt5uKmw== Upgrade: websocket Sec-WebSocket-Version: 13
If the server understands the WebSocket protocol, it agrees to protocol switching through the upgrade header.
HTTP/1.1 101 WebSocket Protocol Handshake Date: Fri, 10 Feb 2012 17:38:18 GMTConnection: Upgrade Server: Kaazing Gateway Upgrade: WebSocket Access-Control-Allow-Origin: http://websocket.org Access-Control-Allow-Credentials: true Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU= Access-Control-Allow-Headers: content-type
At this time, the HTTP connection is decomposed and replaced by the WebSocket connection in the same underlying TCP/IP connection. The WebSocket connection uses the same HTTP (80) as the HTTPS port (443). By default.
After the connection is established, the WebSocket data frame can send back and forth between the client and the server in full duplex mode. Two types of text and binary frames can be sent simultaneously in two directions. The minimum frame value is two bytes. For text frames, each frame starts from 0 x00 bytes and ends with 0 xff bytes, including utf-8 data. The WebSocket text framework uses a Terminator, while the binary frame uses the prefix length.