diff --git a/lib/socket.ts b/lib/socket.ts index c79ac12c4c..84e7e57979 100644 --- a/lib/socket.ts +++ b/lib/socket.ts @@ -537,7 +537,11 @@ export class Socket extends EventEmitter { if (err) { return this._onerror(err); } - super.emit.apply(this, event); + if (this.connected) { + super.emit.apply(this, event); + } else { + debug("ignore packet received after disconnection"); + } }); }); } diff --git a/test/socket.io.ts b/test/socket.io.ts index a2e04b10ae..803d287cb9 100644 --- a/test/socket.io.ts +++ b/test/socket.io.ts @@ -1787,6 +1787,33 @@ describe("socket.io", () => { }); }); + it("should ignore a packet received after disconnection", (done) => { + const srv = createServer(); + const sio = new Server(srv); + + srv.listen(() => { + const clientSocket = client(srv); + + const success = () => { + clientSocket.close(); + sio.close(); + done(); + }; + + sio.on("connection", (socket) => { + socket.on("test", () => { + done(new Error("should not happen")); + }); + socket.on("disconnect", success); + }); + + clientSocket.on("connect", () => { + clientSocket.emit("test", Buffer.alloc(10)); + clientSocket.disconnect(); + }); + }); + }); + describe("onAny", () => { it("should call listener", (done) => { const srv = createServer();