How does the WebSocket handshake work? It’s really easy, because there’s only one handshake:

  1. First the client sends a handshake packet, in which:

    • Methods must be GET methods
    • The HTTP version cannot be later than 1.1
    • The Upgrade header must be included and the value must be websocket
    • The sec-websocket-key header must be included and the value is a Base64 encoded 16-byte random string
    • The sec-websocket-version header must be included and the value must be 13

    Other optional headers refer to the RFC6455 documentation. Sample request headers are as follows:

    GET ws://localhost:7002/ HTTP/1.1 Host: localhost:7002 Connection: Upgrade Upgrade: websocket Sec- websocket-version: 13 Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh; Q = 0.9, en. Q = 0.8, ja. Q =0.7 sec-websocket-key: yEwVMqDyEwAgAKNzFEzgPw== sec-websocket-extensions: permessage-deflate; client_max_window_bitsCopy the code
  2. After verifying that the handshake packet of the client meets the specifications, the server also sends a handshake packet to the client in the following format:

    • The Connection header must be included and the value must be Upgrade
    • An Upgrade header must be included and the value must be websocket
    • Must contain an SEC-websocket-accept header

    Where, the value of the sec-websocket-accept header is calculated according to the following rules:

    • The fixed string 258eafa5-e914-47DA-95CA-C5AB0DC85b11 is first concatenated to the corresponding value of sec-websocket-key.
    • A sha-1 calculation is performed on the concatenated string
    • The calculated results are Base64 encoded

    The demo code is as follows:

    crypto.createHash('sha1').update(webSocketKey + wsGUID).digest('base64')
    Copy the code

    The sample response header looks like this:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: rVYiZQwHfb4oDr4MkkMYo6lbeaY=
    Copy the code
  3. After receiving the handshake packet from the server, the client verifies that the packet format complies with specifications. (That is, calculate sec-websocket-Accept in the same way as in 2 and compare it with the value in the server handshake packet)