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: socketio#4129
  • Loading branch information
darrachequesne committed Nov 12, 2021
1 parent e6c6485 commit 2319aff
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
14 changes: 9 additions & 5 deletions lib/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,7 @@ export class Socket<
*/
public data: Partial<SocketData> = {};

public connected: boolean;
public disconnected: boolean;
public connected: boolean = false;

private readonly server: Server<
ListenEvents,
Expand Down Expand Up @@ -163,8 +162,6 @@ export class Socket<
} else {
this.id = base64id.generateId(); // don't reuse the Engine.IO id because it's sensitive information
}
this.connected = true;
this.disconnected = false;
this.handshake = this.buildHandshake(auth);
}

Expand Down Expand Up @@ -342,6 +339,7 @@ export class Socket<
*/
_onconnect(): void {
debug("socket connected - writing packet");
this.connected = true;
this.join(this.id);
if (this.conn.protocol === 3) {
this.packet({ type: PacketType.CONNECT });
Expand Down Expand Up @@ -489,7 +487,6 @@ export class Socket<
this.nsp._remove(this);
this.client._remove(this);
this.connected = false;
this.disconnected = true;
this.emitReserved("disconnect", reason);
return;
}
Expand Down Expand Up @@ -631,6 +628,13 @@ export class Socket<
run(0);
}

/**
* Whether the socket is currently disconnected
*/
public get disconnected() {
return !this.connected;
}

/**
* A reference to the request that originated the underlying Engine.IO Socket.
*
Expand Down
19 changes: 19 additions & 0 deletions test/socket.io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2726,6 +2726,25 @@ describe("socket.io", () => {
if (++count === 2) done();
});
});

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

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

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

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

describe("socket middleware", () => {
Expand Down

0 comments on commit 2319aff

Please sign in to comment.