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

Backported from 34f822f
  • Loading branch information
darrachequesne committed Jun 26, 2022
1 parent b1d7eef commit 991eb0b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -332,8 +332,8 @@ Socket.prototype.onack = function (packet) {
Socket.prototype.onconnect = function () {
this.connected = true;
this.disconnected = false;
this.emit('connect');
this.emitBuffered();
this.emit('connect');
};

/**
Expand Down
20 changes: 20 additions & 0 deletions test/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,24 @@ describe('socket', function () {
done();
});
});

it('should emit events in order', function (done) {
var socket = io('/', { autoConnect: false });
var i = 0;

socket.on('connect', function () {
socket.emit('echo', 'second', function () {
expect(++i).to.eql(2);

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

socket.emit('echo', 'first', function () {
expect(++i).to.eql(1);
});

socket.connect();
});
});
4 changes: 4 additions & 0 deletions test/support/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ server.on('connection', function (socket) {
socket.emit('hi');
});

socket.on('echo', function (arg, callback) {
callback(arg);
});

// ack tests
socket.on('ack', function () {
socket.emit('ack', function (a, b) {
Expand Down

0 comments on commit 991eb0b

Please sign in to comment.