close(code, reason)
Calling ws.close() initiates the close handshake — the browser sends a close frame, the server responds with one, and the underlying TCP socket tears down. You can pass an optional close code and reason. The reason is a UTF-8 string, max 123 bytes — long enough for "session expired", short enough to keep the close frame compact.
Application close codes (4000-4999)
The 4000-4999 range is reserved for application-defined codes. Pick a few stable ones for your protocol — 4001 unauthorized, 4029 too many connections, 4040 room not found — and your client can branch on them cleanly. Avoid using 1xxx codes like 1001 or 1011 from application logic; those have RFC meaning.
wasClean tells you the truth
The close event has a wasClean boolean. true means a proper close handshake completed; the code is meaningful. false means the connection died — the code will usually be 1006 and the reason will be empty.