From 7510bc9bb36c1895db78c85684f40a7a76ab643f Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Mon, 12 Jun 2017 13:35:10 +0200 Subject: [PATCH] fix middleware initialization --- lib/index.js | 38 ++++++++++++++++++++++++++------------ lib/namespace.js | 6 ++++-- test/socket.io.js | 13 +++++++++++++ 3 files changed, 43 insertions(+), 14 deletions(-) diff --git a/lib/index.js b/lib/index.js index 3a574ee9b5..0b5f689350 100644 --- a/lib/index.js +++ b/lib/index.js @@ -245,29 +245,43 @@ Server.prototype.attach = function(srv, opts){ // set origins verification opts.allowRequest = opts.allowRequest || this.checkRequest.bind(this); - var self = this; + if (this.sockets.fns.length > 0) { + this.initEngine(srv, opts); + return this; + } + var self = this; var connectPacket = { type: parser.CONNECT, nsp: '/' }; this.encoder.encode(connectPacket, function (encodedPacket){ // the CONNECT packet will be merged with Engine.IO handshake, // to reduce the number of round trips opts.initialPacket = encodedPacket; - // initialize engine - debug('creating engine.io instance with opts %j', opts); - self.eio = engine.attach(srv, opts); + self.initEngine(srv, opts); + }); + return this; +}; + +/** + * Initialize engine + * + * @param {Object} options passed to engine.io + * @api private + */ - // attach static file serving - if (self._serveClient) self.attachServe(srv); +Server.prototype.initEngine = function(srv, opts){ + // initialize engine + debug('creating engine.io instance with opts %j', opts); + this.eio = engine.attach(srv, opts); - // Export http server - self.httpServer = srv; + // attach static file serving + if (this._serveClient) this.attachServe(srv); - // bind to engine events - self.bind(self.eio); - }); + // Export http server + this.httpServer = srv; - return this; + // bind to engine events + this.bind(this.eio); }; /** diff --git a/lib/namespace.js b/lib/namespace.js index 69d07c5c88..3c6b65ca4d 100644 --- a/lib/namespace.js +++ b/lib/namespace.js @@ -99,8 +99,10 @@ Namespace.prototype.initAdapter = function(){ */ Namespace.prototype.use = function(fn){ - debug('removing initial packet'); - delete this.server.eio.initialPacket; + if (this.server.eio) { + debug('removing initial packet'); + delete this.server.eio.initialPacket; + } this.fns.push(fn); return this; }; diff --git a/test/socket.io.js b/test/socket.io.js index 84a252b5fa..bd2e65d2ad 100644 --- a/test/socket.io.js +++ b/test/socket.io.js @@ -2268,6 +2268,19 @@ describe('socket.io', function(){ }); }); }); + + it('should disable the merge of handshake packets', function(done){ + var srv = http(); + var sio = io(); + sio.use(function(socket, next){ + next(); + }); + sio.listen(srv); + var socket = client(srv); + socket.on('connect', function(){ + done(); + }); + }); }); describe('socket middleware', function(done){