Skip to content

Commit 226cc16

Browse files
fix: only set 'connected' to true after middleware execution
The Socket instance is only considered connected when the "connection" event is emitted, and not during the middleware(s) execution. ```js io.use((socket, next) => { console.log(socket.connected); // prints "false" next(); }); io.on("connection", (socket) => { console.log(socket.connected); // prints "true" }); ``` Related: #4129 Backported from 02b0f73
1 parent 05e1278 commit 226cc16

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

lib/socket.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ function Socket(nsp, client, query){
6666
this.conn = client.conn;
6767
this.rooms = {};
6868
this.acks = {};
69-
this.connected = true;
70-
this.disconnected = false;
69+
this.connected = false;
70+
this.disconnected = true;
7171
this.handshake = this.buildHandshake(query);
7272
this.fns = [];
7373
this.flags = {};
@@ -300,6 +300,8 @@ Socket.prototype.leaveAll = function(){
300300

301301
Socket.prototype.onconnect = function(){
302302
debug('socket connected - writing packet');
303+
this.connected = true;
304+
this.disconnected = false;
303305
this.nsp.connected[this.id] = this;
304306
this.join(this.id);
305307
var skip = this.nsp.name === '/' && this.nsp.fns.length === 0;

test/socket.io.js

+19
Original file line numberDiff line numberDiff line change
@@ -2442,6 +2442,25 @@ describe('socket.io', function(){
24422442
if (++count === 2) done();
24432443
});
24442444
});
2445+
2446+
it("should only set `connected` to true after the middleware execution", (done) => {
2447+
const httpServer = http();
2448+
const sio = io(httpServer);
2449+
2450+
const clientSocket = client(httpServer, "/");
2451+
2452+
sio.use((socket, next) => {
2453+
expect(socket.connected).to.be(false);
2454+
expect(socket.disconnected).to.be(true);
2455+
next();
2456+
});
2457+
2458+
sio.on("connection", (socket) => {
2459+
expect(socket.connected).to.be(true);
2460+
expect(socket.disconnected).to.be(false);
2461+
done();
2462+
});
2463+
});
24452464
});
24462465

24472466
describe('socket middleware', function(done){

0 commit comments

Comments
 (0)