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:
- Initiator sends Close frame
- Receiver sends Close frame response after receiving Close frame
- Receiver closes TCP connection
- 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
| Code | Name | Description |
|---|---|---|
| 1000 | Normal Closure | Normal closure |
| 1001 | Going Away | Endpoint going away (e.g., page navigation) |
| 1002 | Protocol Error | Protocol error |
| 1003 | Unsupported Data | Unsupported data type |
| 1005 | No Status Rcvd | Reserved, should not be used in Close frame |
| 1006 | Abnormal Closure | Reserved, indicates abnormal connection closure |
| 1007 | Invalid frame payload data | Invalid frame payload data (e.g., invalid UTF-8) |
| 1008 | Policy Violation | Policy violation |
| 1009 | Message Too Big | Message too large |
| 1010 | Mandatory Ext. | Client expected extension not negotiated |
| 1011 | Internal Error | Server internal error |
| 1015 | TLS handshake | TLS 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) |
+--------+--------+------------------+
Reference Links
- Previous Chapter: 6. Sending and Receiving Data
- Next Chapter: 8. Error Handling
- Detailed Explanation: Closing Process