Skip to content

Commit b21b649

Browse files
fix: handle late HTTP server binding
The following example: ```js const io = new Server(); // without port or HTTP server instrument(io, { auth: false }); io.listen(3000); ``` will now work properly. Related: #49
1 parent 6d58a75 commit b21b649

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

lib/index.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ const initStatsEmitter = (
142142
"server_stats",
143143
Object.assign({}, baseStats, {
144144
uptime: process.uptime(),
145-
clientsCount: io.engine.clientsCount,
145+
clientsCount: io.engine?.clientsCount,
146146
pollingClientsCount: io._pollingClientsCount,
147147
aggregatedEvents: io._eventBuffer.getValuesAndClear(),
148148
namespaces,
@@ -489,7 +489,7 @@ const registerEngineListeners = (io: Server) => {
489489
io._eventBuffer = new EventBuffer();
490490
io._pollingClientsCount = 0;
491491

492-
io.engine.on("connection", (rawSocket: any) => {
492+
const onConnection = (rawSocket: any) => {
493493
io._eventBuffer.push("rawConnection");
494494

495495
if (rawSocket.transport.name === "polling") {
@@ -524,7 +524,20 @@ const registerEngineListeners = (io: Server) => {
524524
rawSocket.on("close", (reason: string) => {
525525
io._eventBuffer.push("rawDisconnection", reason);
526526
});
527-
});
527+
};
528+
529+
if (io.engine) {
530+
io.engine.on("connection", onConnection);
531+
} else {
532+
// io.engine might be undefined if instrument() is called before binding the Socket.IO server to the HTTP server
533+
process.nextTick(() => {
534+
if (io.engine) {
535+
io.engine.on("connection", onConnection);
536+
} else {
537+
debug("WARN: no engine");
538+
}
539+
});
540+
}
528541
};
529542

530543
export function instrument(io: Server, opts: Partial<InstrumentOptions>) {

test/index.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,17 @@ describe("Socket.IO Admin (server instrumentation)", () => {
6767
});
6868
});
6969

70+
it("should work with io.listen()", () => {
71+
const io = new Server();
72+
73+
instrument(io, {
74+
auth: false,
75+
});
76+
77+
io.listen(0);
78+
io.close();
79+
});
80+
7081
describe("authentication", () => {
7182
it("prevents anonymous connection", (done) => {
7283
instrument(io, {

0 commit comments

Comments
 (0)