From aeb748a4802ac73bf29b2a8894cf66a7d8314f24 Mon Sep 17 00:00:00 2001 From: Andy Prock Date: Wed, 9 Nov 2016 10:47:03 -0800 Subject: [PATCH] ensure server close events are being sent --- TcpServer.js | 27 ++++++++++++++++++--------- examples/rctsockets/index.ios.js | 4 ++++ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/TcpServer.js b/TcpServer.js index 3a2157d..96ccab1 100644 --- a/TcpServer.js +++ b/TcpServer.js @@ -40,10 +40,6 @@ function TcpServer(connectionListener: (socket: Socket) => void) { self.emit('connection', socket); }); // $FlowFixMe: suppressing this error flow doesn't like EventEmitter - this._socket.on('close', function() { - self.emit('close'); - }); - // $FlowFixMe: suppressing this error flow doesn't like EventEmitter this._socket.on('error', function(error) { self.emit('error', error); }); @@ -74,7 +70,7 @@ TcpServer.prototype.listen = function() : TcpServer { var host = options.host || '0.0.0.0'; if (callback) { - this.on('listening', callback); + this.once('listening', callback); } this._socket._registerEvents(); @@ -90,15 +86,28 @@ TcpServer.prototype.getConnections = function(callback: (err: ?any, count: numbe }; TcpServer.prototype.address = function() : { port: number, address: string, family: string } { - return this._socket.address(); + return this._socket ? this._socket.address() : {}; }; TcpServer.prototype.close = function(callback: ?() => void) { - if (callback) { - this.on('close', callback); + if (typeof callback === 'function') { + if (!this._socket) { + this.once('close', function close() { + callback(new Error('Not running')); + }); + } else { + this.once('close', callback); + } } - this._socket.end(); + if (this._socket) { + this._socket.end(); + } + + var self = this; + setImmediate(function () { + self.emit('close'); + }); }; // unimplemented net.Server apis diff --git a/examples/rctsockets/index.ios.js b/examples/rctsockets/index.ios.js index 589d1c0..d688f8b 100644 --- a/examples/rctsockets/index.ios.js +++ b/examples/rctsockets/index.ios.js @@ -55,6 +55,10 @@ class RctSockets extends Component { this.updateChatter('error ' + error); }); + server.on('close', () => { + this.updateChatter('server close'); + }); + let client = net.createConnection(serverPort, () => { this.updateChatter('opened client on ' + JSON.stringify(client.address())); client.write('Hello, server! Love, Client.');