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: https://github.com/socketio/socket.io/issues/5258
This commit is contained in:
Suraj Rana
2024-12-12 21:13:12 +05:30
committed by Damien Arrachequesne
parent cdae01983a
commit d19928e8d8
2 changed files with 38 additions and 3 deletions

View File

@@ -542,8 +542,7 @@ export class Socket<
args.push((err, ...responseArgs) => {
if (packet !== this._queue[0]) {
// the packet has already been acknowledged
return;
return debug("packet [%d] already acknowledged", packet.id);
}
const hasError = err !== null;
if (hasError) {
@@ -834,8 +833,8 @@ export class Socket<
this._pid = pid; // defined only if connection state recovery is enabled
this.connected = true;
this.emitBuffered();
this.emitReserved("connect");
this._drainQueue(true);
this.emitReserved("connect");
}
/**

View File

@@ -110,4 +110,40 @@ describe("retry", () => {
}, 100);
});
});
it.only("should not emit a packet twice in the 'connect' handler", () => {
return wrap((done) => {
const socket = io(BASE_URL, {
forceNew: true,
retries: 3,
});
const received: string[] = [];
const sent: string[] = [];
socket.io.engine.on("packetCreate", ({ data }) => {
sent.push(data);
});
socket.io.engine.on("packet", ({ data }) => {
received.push(data);
});
socket.on("connect", () => {
socket.emit("echo", null);
});
setTimeout(() => {
expect(sent).to.eql(["0", '20["echo",null]']);
expect(received.length).to.eql(3);
// 1: engine.io OPEN packet
// 2: socket.io CONNECT packet
// 3: ack packet
expect(received[2]).to.eql("30[null]");
success(done, socket);
}, 100);
});
});
});