The WebSocket protocol is a two-way communication protocol that is based on TCP and transmits data over TCP as HTTP, but it differs from HTTP by a maximum of two points: 1. WebSocket is a two-way communication protocol, after establishing a connection, the WebSocket server and Browser/ua can actively send or receive data to each other, just like a socket, The difference is that WebSocket is a simple analog socket protocol based on Web, 2. WebSocket need to be connected via a handshake, similar to TCP It also requires a handshake connection between the client and server to communicate with each other after the connection is successful.
Here is a simple timing diagram to build the handshake:
Here is a brief explanation of the WebSocket handshake process.
When the Web application calls the new WebSocket (URL) interface, browser begins the process of establishing a handshake connection with the Webserver address as a URL.
1. Browser with the WebSocket server through a TCP three handshake to establish a connection, if the connection fails, then the subsequent procedure will not be executed, the Web application will receive an error message notification.
2. After TCP establishes the connection successfully, BROWSER/UA transmits the WebSocket supported version number through the HTTP protocol, the Word version number of the Protocol, the original address, the host address and so on some column fields to the server side.
For example: [HTML] view plain copy get /chat http/1.1 host: server.example.com upgrade: websocket connection: upgrade sec-websocket-key:dghlihnhbxbszsbub25jzq== origin: http://example.com sec-websocket-protocol: chat,superchat sec-websocket-version: 13
3. websocket server receives the handshake request sent by Browser/ua, if the packet data and format is correct, the client and server-side protocol version number matches, and so on, accept this handshake connection , and the corresponding data reply, the same reply packet is also transmitted using the HTTP protocol. [HTML] view plain copy http/1.1 101 switching protocols upgrade: websocket connection: upgrade sec-websocket-accept:s3pplmbitxaq9kygzzhzrbk+xoo= sec-websocket-protocol: chat
4. Browser received the server reply to the packet, if the contents of the packet, the format is not a problem, it means that the connection is successful, triggering the OnOpen message, the web developer can at this time through the send interface to the server to send data. Otherwise, the handshake connection fails, and the Web application receives the ONERROR message and knows why the connection failed.