Security, experiments and writing · JavaScript · socket.io

Lost acks in socket.io

socket.io lets you ask the server to confirm a message. What happens if the connection drops before the answer comes? This is a small test of the four ways to ask, with socket.io 4.8.3. It is a study of how the library behaves, not a change to it.

socket.io JavaScript Real-time Testing

Try it

Pick a way to send, then run it. The server hangs up instead of answering. This page replays the results from the real test below.

Results

How it was sentWhen the connection dropped
emit + callbackNever called (waited 3 seconds)
timeout(1000).emit + callbackCalled with an error after about 10 ms
emitWithAckRejected with an error after about 10 ms
timeout(1000).emitWithAckRejected with an error after about 10 ms

The error is "socket has been disconnected". It comes as soon as the connection is gone, so the one second timeout is never reached.

Why

A plain callback has nowhere to put an error.

It only expects the server's answer. If the client called it with an error, code that isn't ready for one would read the error as data. So on disconnect the client drops it without calling it.

The other three can take an error.

A callback after timeout() gets the error as its first argument, and emitWithAck returns a promise that can be rejected. The client tells them right away.

What to use.

If it matters that a message arrived, use timeout().emitWithAck(). It also covers a server that stays connected but never answers.

The test

// What happens to an acknowledgement when the connection drops before it arrives?
// Run it: npm install socket.io socket.io-client, then: node ack-test.mjs
import { Server } from "socket.io";
import { io as connect } from "socket.io-client";

function run(name, send) {
  return new Promise((resolve) => {
    // a server that always hangs up instead of answering
    const server = new Server(0);
    server.on("connection", (s) => s.on("test", () => s.disconnect(true)));

    const port = server.httpServer.address().port;
    const client = connect(`http://localhost:${port}`, { reconnection: false });
    let done = false;
    function finish(result) {
      if (done) return;
      done = true;
      console.log(`${name}: ${result}`);
      client.close();
      server.close();
      resolve();
    }
    client.on("connect", () => send(client, finish));
    setTimeout(() => finish("never called"), 3000);
  });
}

await run("emit + callback", (c, finish) =>
  c.emit("test", {}, () => finish("called")));

await run("timeout + callback", (c, finish) =>
  c.timeout(1000).emit("test", {}, (err) => finish(err)));

await run("emitWithAck", (c, finish) =>
  c.emitWithAck("test", {}).then(finish, finish));

await run("timeout + emitWithAck", (c, finish) =>
  c.timeout(1000).emitWithAck("test", {}).then(finish, finish));