How do you close a WebSocket connection?
Answer
A WebSocket connection is closed gracefully using ws.close(code, reason). The close code is a numeric status (e.g., 1000 for normal closure, 1001 for going away, 1008 for policy violation). The reason is an optional human-readable string explaining why the connection is closing. A graceful close sends a close frame to the other party, which must respond with its own close frame before the TCP connection is terminated — this ensures both sides know the connection is intentionally ending. You can detect close initiation by the server by listening to the client's close event. Calling ws.close() without arguments sends close code 1000. If the connection is force-closed (network failure), no close frame is sent and the other party detects it via timeout or TCP RST.