einaros/ws — Issue #31: Missing 'close' event when using WebSocket as a client
Author: ypocat
Created: 2012-02-26 22:20:06+00:00
State: open

Based on the WebSocket spec, section [Feedback from the protocol](http://dev.w3.org/html5/websockets/#feedback-from-the-protocol), the last part reads:

> "When the WebSocket connection is closed, ...
> 2. ... fire a simple event named error ...
> 3. Create an event ... with the event named close ... and dispatch the event"

Now, when using the WebSocket object to initiate a connection to a remote WebSocket server, in multiple cases only the `error` event is emitted, but no `close` event.

I have mapped the cases and the relevant source locations. So, this happens:

1. When the server closes the connection, the listeners are cleaned from the WebSocket too early, and the `close` event is not delivered, [see here, line 485](https://github.com/einaros/ws/blob/1243c3fc3ad8cd0184e47f5b6a3b5721e97b0199/lib/WebSocket.js#L485) (perhaps it's OK to leave the listeners there, for either the user or the GC to clean them)

2. When the client is connecting to a server which is not listening, only the error event is emitted, [see here, line 451](https://github.com/einaros/ws/blob/1243c3fc3ad8cd0184e47f5b6a3b5721e97b0199/lib/WebSocket.js#L451) (this is ambiguous in the spec, because it says _when the connection is closed_ and here the connection wasn't established, but indeed all browsers emit a `close` here)

3. And the last one I haven't experienced, but by the looks it's the same case, when the server key is invalid, [see here, line 462](https://github.com/einaros/ws/blob/1243c3fc3ad8cd0184e47f5b6a3b5721e97b0199/lib/WebSocket.js#L462) (again, I think this should be consistent, e.g. when a user reconnection code waits for a `close` event, it should get it)