This article mainly introduces the principles of implementing the WebSocket protocol in HTML5 to help beginners understand the WebSocket protocol. If you need it, you can refer to the WebSocket Protocol for the purpose of working on the existing network infrastructure. As part of this design principle, the Protocol Specification for WebSocket connection defines an HTTP connection as its initial lifecycle to ensure its full backward compatibility with the pre-WebSocket world. Generally, 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. The Code is as follows:
The Code is as follows:
GET ws: // echo.websocket.org /? Encoding = text https/1.1
Origin: http://websocket.org
Cookie: _ utma = 99as
Connection: Upgrade
Host: echo.websocket.org
Sec-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.
The Code is as follows:
HTTP/1.1 101 WebSocket Protocol Handshake
Date: Fri, 10 Feb 2012 17:38:18 GMT
Connection: 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.