theturtle32 / WebSocket-Node

A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

this.socket.end() not sent to browser on reload and no 'end' event emitted

terje-rosenlund opened this issue · comments

STATE_PEER_REQUESTED_CLOSE (peer_requested_close) is sendt by the browser eg. when a page is reloaded

The second if-statement in WebSocketConnection.js, WebSocketConnection.prototype.handleSocketEnd:

if (this.state !== STATE_PEER_REQUESTED_CLOSE && 
	this.state !== STATE_ENDING) {
  this._debug('  --- UNEXPECTED socket end.');
  this.socket.end();
}

That means no reply to a valid browser message which is not according to spec as far as I know

I'm using websocket.server in a nodejs server application which are using async/wait and promises to handle messages
That implies that a socket may be disconnected while awaiting which causes exceptions on all references to the disconnected connection
The 'close' event is useless in this situation because it is emitted by handleSocketClose after the connection has been fully closed and the socket is no longer connected

The 'end' event on the other hand would be more usefull because it's received before the connection has been closed but this event is not emitted by handleSocketEnd
Is there a reason for this?

Receiving that event will give us time to prevent exceptions on disconnected connections

Suggested change:

// When using the TLS module, sometimes the socket will emit 'end'
// after it emits 'close'.  I don't think that's correct behavior,
// but we should deal with it gracefully by ignoring it.
if (this.state === STATE_CLOSED) {
	this._debug('  --- Socket \'end\' after \'close\'');
	// return; // MOD-TR: removed
}
else if (this.state !== STATE_PEER_REQUESTED_CLOSE &&
	this.state !== STATE_ENDING) {
	this._debug('  --- UNEXPECTED socket end.');
	//this.socket.end(); // MOD-TR: BUG, moved below
}
else {
	this.socket.end(); // MOD-TR: moved from abow
	this.emit('end', this.closeReasonCode, this.closeDescription); // MOD-TR: Added
}