Video in progress

How is a WebSocket connection closed, and what do the close codes 1000, 1001 and 1006 mean?

One side sends a close frame, the other answers with a close frame too, and then TCP is closed. 1000 is a normal close, 1001 means a side is going away (tab closed, server shutting down), 1006 means no close frame arrived at all and the connection dropped abruptly.

📖 Answer

Close codes are very useful when debugging:

Code Meaning Typical cause
1000 normal ws.close() was called
1001 going away tab closed, server restart
1006 abnormal network dropped, proxy timeout, process killed
1008 policy violation not allowed
1009 too big message larger than the limit
1011 server error exception in the handler

1006 is never sent inside a frame. The browser sets it itself and it means "there was no close handshake". If 1006 shows up a lot in production, the first thing I check is the idle timeout of the proxy or load balancer.

In Spring you can close it yourself:

session.close(CloseStatus.POLICY_VIOLATION.withReason("token eskirgan"));

Logging status.getCode() inside afterConnectionClosed makes it much easier to find the reason for disconnects.