SoFunction
Updated on 2025-04-14

About WebSocket protocol status code analysis

WebSocket protocol status code analysis

1. Introduction

The WebSocket protocol is a TCP-based full-duplex communication protocol that allows real-time two-way communication between clients and servers.

During WebSocket communication, the server and client will use status codes to indicate the status or error information of the current communication.

2. Overview of WebSocket Protocol Status Code

The WebSocket protocol status code is a 16-bit integer that represents the status of a WebSocket connection. The first number of the status code represents the classification of the status, and the last three numbers represent the specific status.

According to the specifications of the WebSocket protocol, status codes can be divided into the following categories:

  • 1xxx: represents an information status code, used to pass some non-error information.
  • 2xxx: indicates the success status code, which is used to indicate the connection is successful or the operation is successful.
  • 3xxx: Redirecting status code, used to indicate that further operations are required to complete the request.
  • 4xxx: indicates the client error status code, which is used to indicate that the request sent by the client is incorrect.
  • 5xxx: Indicates the server error status code, which means that the server cannot complete the request.

Common WebSocket protocol status codes are:

  • 1000: Close normally
  • 1001: Terminal leave
  • 1002: Protocol Error
  • 1003: Data type error
  • 1005: Unable to receive
  • 1006: Connection closing exception
  • 1011: The server encountered an exception

3. Detailed explanation of the status code of WebSocket protocol

3.1 WebSocket protocol status code 1000: normally closed

  • The status code 1000 indicates that the WebSocket connection is closed normally.
  • When the server or client decides to close the connection, a status code 1000 will be sent to the other party, indicating that the reason for the connection is normal.

3.2 WebSocket protocol status code 1001: Terminal departure

  • The status code 1001 indicates that the client leaves.
  • When the client actively closes the connection, the status code 1001 will be sent to the server, indicating that the client is leaving.

3.3 WebSocket protocol status code 1002: protocol error

  • Status code 1002 indicates a protocol error.
  • When the data received by the server or client does not comply with the specifications of the WebSocket protocol, the status code 1002 will be sent to the other party, indicating that the protocol is incorrect.

3.4 WebSocket protocol status code 1003: data type error

  • The status code 1003 indicates that the data type is incorrect.
  • When the data type received by the server or client does not meet expectations, a status code 1003 will be sent to the other party, indicating that the data type is incorrect.

3.5 WebSocket protocol status code 1005: Unable to receive

  • The status code 1005 indicates that data cannot be received.
  • When the server or client cannot receive data for some reason, the status code 1005 will be sent to the other party, indicating that it cannot receive it.

3.6 WebSocket protocol status code 1006: Connection closing exception

  • The status code 1006 indicates that the connection is closed abnormally.
  • When the server or client encounters an abnormality when closing the connection, the status code 1006 will be sent to the other party, indicating that the connection is closed abnormally.

3.7 WebSocket protocol status code 1011: The server encounters an exception

  • The status code 1011 indicates that the server encountered an exception.
  • When the server encounters an exception when processing WebSocket requests, the status code 1011 will be sent to the client, indicating that the server has encountered an exception.

4. Usage scenarios of WebSocket protocol status code

When using the WebSocket protocol, we need to correctly handle the status code and the corresponding error situation.

Here are some examples of handling WebSocket protocol status codes:

// Client code exampleconst socket = new WebSocket('ws://');

 = function() {
```javascript
    ('WebSocket connection is open');
};

 = function(event) {
    ('Received the message:', );
};

 = function(event) {
    if ( === 1000) {
        ('WebSocket connection is closed normally');
    } else if ( === 1001) {
        ('WebSocket connection is closed by the client');
    } else if ( === 1006) {
        ('WebSocket connection closing exception');
    } else {
        ('WebSocket connection is closed, status code:', );
    }
};

 = function(error) {
    ('An error occurred in WebSocket connection:', error);
};

In the above example, we use four event handlers from WebSocket to handle different status codes and error cases.

When the connection is successfully opened, it will be triggeredonopenEvent; triggers when a message is receivedonmessageEvent; triggers when the connection is closedoncloseEvent; triggers when an error occurs in the connectiononerrorevent.

existoncloseIn events, we process them according to different status codes.

5. Extension of WebSocket protocol status code

In addition to using the status code specified by the WebSocket protocol, we can also customize the status code of the WebSocket protocol to meet specific needs.

Here is an example of a custom WebSocket protocol status code:

// Server code exampleconst http = require('http');
const server = ();

('upgrade', (request, socket, head) => {
    const responseHeaders = [
        'HTTP/1.1 101 Switching Protocols',
        'Upgrade: websocket',
        'Connection: Upgrade',
        'Sec-WebSocket-Accept: ' + generateAcceptKey(['sec-websocket-key']),
        'Sec-WebSocket-Protocol: custom-protocol',
        'Custom-Status: 2000',
        '\r\n'
    ];

    (('\r\n'));

    // ... Handle WebSocket connections});

function generateAcceptKey(key) {
    // Generate the value of the Sec-WebSocket-Accept header    // ...
}

(8080);

In the above example, we added a custom header field to the response header on the serverCustom-Status, used to represent a custom status code.

After receiving the server response, the client canCustom-StatusThe header field is used to determine the custom status code.

Summarize

The WebSocket protocol status code is a mechanism used to represent the status or error message of WebSocket connection.

We can handle the corresponding situation according to different status codes to ensure the stability and reliability of WebSocket communication. At the same time, we can also extend the WebSocket protocol status code to meet specific needs.

References:

  • RFC 6455 - The WebSocket Protocol

The above is personal experience. I hope you can give you a reference and I hope you can support me more.