Skip to content

Commit

Permalink
fix: only set 'connected' to true after middleware execution
Browse files Browse the repository at this point in the history
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
  • Loading branch information
darrachequesne committed Jun 26, 2022
1 parent 05e1278 commit 226cc16
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/socket.js
Expand Up @@ -66,8 +66,8 @@ function Socket(nsp, client, query){
this.conn = client.conn;
this.rooms = {};
this.acks = {};
this.connected = true;
this.disconnected = false;
this.connected = false;
this.disconnected = true;
this.handshake = this.buildHandshake(query);
this.fns = [];
this.flags = {};
Expand Down Expand Up @@ -300,6 +300,8 @@ Socket.prototype.leaveAll = function(){

Socket.prototype.onconnect = function(){
debug('socket connected - writing packet');
this.connected = true;
this.disconnected = false;
this.nsp.connected[this.id] = this;
this.join(this.id);
var skip = this.nsp.name === '/' && this.nsp.fns.length === 0;
Expand Down
19 changes: 19 additions & 0 deletions test/socket.io.js
Expand Up @@ -2442,6 +2442,25 @@ describe('socket.io', function(){
if (++count === 2) done();
});
});

it("should only set `connected` to true after the middleware execution", (done) => {
const httpServer = http();
const sio = io(httpServer);

const clientSocket = client(httpServer, "/");

sio.use((socket, next) => {
expect(socket.connected).to.be(false);
expect(socket.disconnected).to.be(true);
next();
});

sio.on("connection", (socket) => {
expect(socket.connected).to.be(true);
expect(socket.disconnected).to.be(false);
done();
});
});
});

describe('socket middleware', function(done){
Expand Down

0 comments on commit 226cc16

Please sign in to comment.