Skip to content

Commit

Permalink
fix: ensure buffered events are sent in order
Browse files Browse the repository at this point in the history
Before this commit, an event sent in the "connect" handler could be
sent before the events that were buffered while disconnected.

```js
socket.on("connect", () => {
  socket.emit("bar");
});

socket.emit("foo"); // buffered while disconnected
```

In the example above, the "bar" event was sent first, which is not
correct.

Related: #1458
  • Loading branch information
darrachequesne committed May 6, 2021
1 parent dd2a8fc commit 34f822f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,8 +384,8 @@ export class Socket<
this.id = id;
this.connected = true;
this.disconnected = false;
this.emitReserved("connect");
this.emitBuffered();
this.emitReserved("connect");
}

/**
Expand Down
20 changes: 20 additions & 0 deletions test/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,26 @@ describe("socket", function () {
);
});

it("should emit events in order", (done) => {
const socket = io("/", { autoConnect: false });
let i = 0;

socket.on("connect", () => {
socket.emit("echo", "second", () => {
expect(++i).to.eql(2);

socket.disconnect();
done();
});
});

socket.emit("echo", "first", () => {
expect(++i).to.eql(1);
});

socket.connect();
});

describe("volatile packets", () => {
it("should discard a volatile packet when the socket is not connected", (done) => {
const socket = io({ forceNew: true, autoConnect: false });
Expand Down
4 changes: 4 additions & 0 deletions test/support/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ server.on("connection", (socket) => {
socket.emit("hi");
});

socket.on("echo", (arg, cb) => {
cb(arg);
});

// ack tests
socket.on("ack", () => {
socket.emit("ack", (a, b) => {
Expand Down

0 comments on commit 34f822f

Please sign in to comment.