Skip to content

Commit d19928e

Browse files
backendsurajdarrachequesne
authored andcommitted
fix(sio-client): drain queue before emitting "connect" (#5259)
When the `retries` option was enabled, an event emitted in the "connect" handler would be sent twice. Related: #5258
1 parent cdae019 commit d19928e

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

packages/socket.io-client/lib/socket.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -542,8 +542,7 @@ export class Socket<
542542

543543
args.push((err, ...responseArgs) => {
544544
if (packet !== this._queue[0]) {
545-
// the packet has already been acknowledged
546-
return;
545+
return debug("packet [%d] already acknowledged", packet.id);
547546
}
548547
const hasError = err !== null;
549548
if (hasError) {
@@ -834,8 +833,8 @@ export class Socket<
834833
this._pid = pid; // defined only if connection state recovery is enabled
835834
this.connected = true;
836835
this.emitBuffered();
837-
this.emitReserved("connect");
838836
this._drainQueue(true);
837+
this.emitReserved("connect");
839838
}
840839

841840
/**

packages/socket.io-client/test/retry.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,4 +110,40 @@ describe("retry", () => {
110110
}, 100);
111111
});
112112
});
113+
114+
it.only("should not emit a packet twice in the 'connect' handler", () => {
115+
return wrap((done) => {
116+
const socket = io(BASE_URL, {
117+
forceNew: true,
118+
retries: 3,
119+
});
120+
121+
const received: string[] = [];
122+
const sent: string[] = [];
123+
124+
socket.io.engine.on("packetCreate", ({ data }) => {
125+
sent.push(data);
126+
});
127+
128+
socket.io.engine.on("packet", ({ data }) => {
129+
received.push(data);
130+
});
131+
132+
socket.on("connect", () => {
133+
socket.emit("echo", null);
134+
});
135+
136+
setTimeout(() => {
137+
expect(sent).to.eql(["0", '20["echo",null]']);
138+
139+
expect(received.length).to.eql(3);
140+
// 1: engine.io OPEN packet
141+
// 2: socket.io CONNECT packet
142+
// 3: ack packet
143+
expect(received[2]).to.eql("30[null]");
144+
145+
success(done, socket);
146+
}, 100);
147+
});
148+
});
113149
});

0 commit comments

Comments
 (0)