Skip to main content

7. Closing the Connection

7.1 Definitions

7.1.1 Closing the WebSocket Connection

Closing the WebSocket connection means closing the underlying TCP connection.

7.1.2 Start the WebSocket Closing Handshake

Send a Close control frame to initiate the closing handshake.

7.1.3 The WebSocket Closing Handshake is Started

The handshake starts when either endpoint sends a Close frame.

7.1.4 The WebSocket Connection is Closed

The connection is considered closed when the underlying TCP connection is closed.

7.1.5 The WebSocket Connection Close Code

The status code included in the Close frame.

7.1.6 The WebSocket Connection Close Reason

The optional textual reason in the Close frame.

7.1.7 Fail the WebSocket Connection

Immediately close the connection due to an error, without sending a Close frame.

7.2 Abnormal Closures

7.2.1 Client-Initiated Closure

When the client detects an error, it should close the connection.

7.2.2 Server-Initiated Closure

When the server detects an error, it should close the connection.

7.2.3 Recovering from Abnormal Closure

Applications should implement reconnection mechanisms.

7.3 Normal Closure of Connections

Normal closure process:

  1. Initiator sends Close frame
  2. Receiver sends Close frame response after receiving Close frame
  3. Receiver closes TCP connection
  4. Initiator also closes TCP connection after receiving Close frame
// Client normal closure
ws.close(1000, 'Normal closure');

// Server-side handling
ws.on('close', (code, reason) => {
console.log(`Connection closed: ${code} - ${reason}`);
});

7.4 Status Codes

7.4.1 Defined Status Codes

CodeNameDescription
1000Normal ClosureNormal closure
1001Going AwayEndpoint going away (e.g., page navigation)
1002Protocol ErrorProtocol error
1003Unsupported DataUnsupported data type
1005No Status RcvdReserved, should not be used in Close frame
1006Abnormal ClosureReserved, indicates abnormal connection closure
1007Invalid frame payload dataInvalid frame payload data (e.g., invalid UTF-8)
1008Policy ViolationPolicy violation
1009Message Too BigMessage too large
1010Mandatory Ext.Client expected extension not negotiated
1011Internal ErrorServer internal error
1015TLS handshakeTLS handshake failure (reserved)

7.4.2 Reserved Status Code Ranges

  • 0-999: Not used
  • 1000-2999: Protocol defined
  • 3000-3999: Library/framework use
  • 4000-4999: Application use

Close Frame Structure

+--------+--------+------------------+
| Status | Reason |
| Code | (optional) |
| (2 bytes)| (UTF-8 text) |
+--------+--------+------------------+