WebSocket is a network communication protocol, the RFC 6455 defines its communication standard, is a server-push technology
Because HTTP stateless, connectionless characteristics of one-way communication, leading to the HTTP protocol can not be achieved server initiates a message to the client, the server can not change the status of immediate notification to the client
WebSocket connection allows full-duplex communication between the client and server, only once to establish a connection can always hold, avoiding the waste caused by multiple HTTP connections
Based on multi-threaded or multi-process servers can not apply to WebSocket, as it seeks to open a connection to process the request as soon as possible, and then close the connection. Any actual WebSockets server are required to implement an asynchronous server
Brief
WebSocket is compatible with HTTP, the default port is 80 and 443, the handshake phase uses the HTTP protocol
The protocol identifier is ws (if encryption was wss), server URL is the URL
WebSocket handshake
Client request
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
Add the following fields in the HTTP request header indicating WebSocket protocol is initiated
Upgrade: websocket
Connection: Upgrade
In addition these fields indicate
Sec-WebSocket-Key
random values encoded base 64, for preventing the proxy server cache WebSocket resend request
Sec-WebSocket-Protocol
string user-defined, represents the requested service
Sec-WebSocket-Version
protocol version
Server response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
The connection is established, switch to the WebSocket protocol
Sec-WebSocket-Accept: After confirmation server, the encrypted Sec-WebSocket-Key
reference:
WebSocket Tutorial - Ruan Yifeng's blog
WebSocket is what principle? Why can achieve lasting connection? -- Know almost