Migrating from Socket.IO

A Socket.IO game server is usually one Node process holding every game in a Map, with Socket.IO rooms as broadcast channels over it. On IRT each game is a room, run by room code you write with @irtio/room, addressed by a room ID, with its own state that’s synced to its clients and saved when the room hibernates. The Map, the "state" events and the seat bookkeeping go away, and what’s left is the game’s rules.

There is no compatibility layer. IRT doesn’t speak the Socket.IO protocol, and a Socket.IO server can’t run in a room host: Socket.IO rooms are channels inside one process, and IRT rooms hibernate and wake in whichever room host has space. You rewrite the server’s handlers as room hooks and the client against @irtio/client; handlers usually carry over with small changes.

This page describes Socket.IO 4.

Concept map

Socket.IO 4 IRT
new Server() and io.on("connection", ...) A room module, export default defineRoom({...}). IRT runs it for each room on its own
socket.join(roomId) connect(roomId), relative to the page’s irt-project meta tag, or connect("https://rooms.irt.io/<project>/<room ID>"): a connection belongs to one room. room.close() leaves it
A socket in several rooms A client in several rooms holds a connection to each
A Map of game state keyed by room room.state, entities and private state, declared in a schema and synced to clients as deltas
io.to(roomId).emit("state", game) after each change Nothing: changes to entities go out as soon as the code that made them yields, or at the end of each tick in a room with a tickRate
socket.id conn.id for the connection, conn.player for the player, stable across reconnects
socket.data conn.data, not saved
socket.handshake.auth and io.use middleware Player tokens checked by the router; conn.meta holds their meta claim. onJoin can room.kick(conn)
socket.on("event", handler) One onMessage(room, conn, message) hook; switch on a type field of your own
socket.emit from the server room.send(conn, msg)
io.to(roomId).emit room.broadcast(msg)
socket.to(roomId).emit room.broadcast(msg, { except: conn })
An ack callback, or emitWithAck, from the client Calls: await room.calls.name(args), answered by calls.name(args, { room, connection }) in the room
socket.timeout(ms).emitWithAck(...) room.calls.name(args, { timeout: ms }); 10 seconds by default
socket.volatile.emit send(msg, { unreliable: true })
socket.on("disconnect") onLeave(room, conn)
setInterval game loops tickRate and onTick(room, dt). A room with no loop leaves tickRate out and sends its changes as they happen
Client connect, disconnect events and reconnection The reconnecting, open and close events, with room.addEventListener. Reconnecting and resyncing are automatic
Connection state recovery Automatic: a reconnecting client gets the full state again
Long-polling, then upgrade to WebSocket WebTransport, with WebSocket as the fallback. No long-polling

A game, ported

Tic-tac-toe in rooms named by an ID the players share. The first two players take x and o, moves are acknowledged, and players can chat.

In Socket.IO

// server.ts (Socket.IO 4)
import { Server } from "socket.io";

type Game = { cells: string[]; x?: string; o?: string; turn: "x" | "o"; winner: string };
const games = new Map<string, Game>();
const io = new Server(3000, { cors: { origin: "https://ttt.example.com" } });

io.on("connection", (socket) => {
  socket.on("join", (roomId: string, ack) => {
    let game = games.get(roomId);
    if (!game) games.set(roomId, (game = { cells: Array(9).fill(""), turn: "x", winner: "" }));
    const mark = !game.x ? "x" : !game.o ? "o" : null;
    if (!mark) return ack({ error: "room full" });
    game[mark] = socket.id;
    socket.data.roomId = roomId;
    socket.join(roomId);
    ack({ mark });
    io.to(roomId).emit("state", game);
  });

  socket.on("play", (cell: number, ack) => {
    const game = games.get(socket.data.roomId);
    if (!game || game.winner || game[game.turn] !== socket.id || game.cells[cell] !== "") {
      return ack({ error: "not your move" });
    }
    game.cells[cell] = game.turn;
    game.winner = winnerOf(game.cells);
    game.turn = game.turn === "x" ? "o" : "x";
    ack({ ok: true });
    io.to(socket.data.roomId).emit("state", game);
  });

  socket.on("chat", (text: string) => {
    socket.to(socket.data.roomId).emit("chat", { from: socket.id, text });
  });

  socket.on("disconnect", () => {
    const game = games.get(socket.data.roomId);
    if (game?.x === socket.id) game.x = undefined;
    if (game?.o === socket.id) game.o = undefined;
  });
});
// client.ts (socket.io-client 4)
import { io } from "socket.io-client";

const socket = io("https://ttt.example.com");
const { mark, error } = await socket.emitWithAck("join", "kitchen-table");
socket.on("state", (game) => render(game));
socket.on("chat", ({ from, text }) => console.log(from, text));

const reply = await socket.emitWithAck("play", 4);
if (reply.error) console.log(reply.error);

The Map is lost when the process restarts, a dropped player loses their seat because socket.id changes on reconnect unless connection state recovery restores it, and running a second process needs an adapter and sticky sessions.

In IRT

The schema, shared by room and client, declares the board and the play call. parse checks the cell on the room before the handler sees it:

// schema.ts
import { defineCalls, defineSchema, entity, json } from "@irtio/room";

export const Board = entity("board", {
  cells: json<string[]>(Array(9).fill("")),
  x: "string",
  o: "string",
  turn: "string",
  winner: "string",
});

export const schema = defineSchema({
  state: Board,
  calls: defineCalls<{ play(args: { cell: number }): string }>({
    play(raw) {
      const cell = (raw as { cell?: unknown } | null)?.cell;
      if (typeof cell !== "number" || !Number.isInteger(cell) || cell < 0 || cell > 8) throw new Error("cell is 0 to 8");
      return { cell };
    },
  }),
});

The room. Seats are player IDs, so a player who reconnects, or reloads the page, still has theirs. A third player watches. The game has no loop, so the room has no tickRate, and a move goes out as soon as its call has run:

// room.ts
import { defineRoom } from "@irtio/room";
import { schema } from "./schema.js";

const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];

function winnerOf(cells: string[]): string {
  for (const [a, b, c] of LINES) if (cells[a!] && cells[a!] === cells[b!] && cells[a!] === cells[c!]) return cells[a!]!;
  return cells.every((m) => m) ? "draw" : "";
}

export default defineRoom({
  schema,
  onCreate(room) {
    room.state.turn = "x";
  },
  onJoin(room, conn) {
    const s = room.state;
    if (s.x === conn.player || s.o === conn.player) return;
    if (!s.x) s.x = conn.player;
    else if (!s.o) s.o = conn.player;
  },
  onMessage(room, conn, message) {
    const m = message as { type?: unknown; text?: unknown } | null;
    if (m?.type !== "chat" || typeof m.text !== "string") return;
    room.broadcast({ type: "chat", from: conn.player, text: m.text.slice(0, 200) }, { except: conn });
  },
  calls: {
    play({ cell }, { room, connection }) {
      const s = room.state;
      const mover = s.turn === "x" ? s.x : s.o;
      if (s.winner || mover !== connection.player || s.cells[cell] !== "") throw new Error("not your move");
      // A json field is sent when it's assigned, so build a new array.
      s.cells = s.cells.map((m, i) => (i === cell ? s.turn : m));
      s.winner = winnerOf(s.cells);
      s.turn = s.turn === "x" ? "o" : "x";
      return s.cells[cell]!;
    },
  },
});

The client. There’s no join event: connecting is joining, and the client reads its seat from the state. Rooms named by the players need players.createRooms on, which is the default, so the first connection creates the room:

// client.ts
import { connect, IrtError } from "@irtio/client";
import { schema } from "./schema.js";

// The page declares <meta name="irt-project" content="https://rooms.irt.io/tic-tac-toe/">.
const room = await connect("kitchen-table", { schema });
const mark = room.state.x === room.player ? "x" : room.state.o === room.player ? "o" : "watching";
console.log("you are", mark);

room.addEventListener("update", () => console.log(room.state.cells?.join(""), room.state.turn, room.state.winner));
room.addEventListener("message", (e) => console.log("chat", e.data));

export async function play(cell: number) {
  try {
    await room.calls.play({ cell });
  } catch (e) {
    if (e instanceof IrtError) console.log(e.message);
    else throw e;
  }
}

export function chat(text: string) {
  room.send({ type: "chat", text });
}

A room ID anyone can guess is fine for a demo. For private tables, use createRoom({ joinCode: true }) and share the code; see Games without a backend. To turn the third player away instead of letting them watch, create rooms with maxPlayers: 2, and a third connection closes with 4003.

Its tests

// room.test.ts
import { testRoom } from "@irtio/testing";
import { expect, test } from "vitest";
import room from "./room.js";

test("players take turns, and the room refuses moves out of turn", async () => {
  const t = testRoom(room);
  const alice = await t.connect({ player: "alice" });
  const bob = await t.connect({ player: "bob" });
  expect(t.live.state).toMatchObject({ x: "alice", o: "bob", turn: "x" });

  expect(await t.settle(alice.client.calls.play({ cell: 4 }))).toBe("x");
  await expect(alice.client.calls.play({ cell: 0 })).rejects.toThrow("not your move");
  await expect(bob.client.calls.play({ cell: 4 })).rejects.toThrow("not your move");
  await expect(bob.client.calls.play({ cell: 9 })).rejects.toThrow("cell is 0 to 8");
  expect(bob.client.state.cells).toEqual(["", "", "", "", "x", "", "", "", ""]);
});

test("a player keeps their seat across a reconnect and a hibernation", async () => {
  const t = testRoom(room);
  const alice = await t.connect({ player: "alice" });
  await t.connect({ player: "bob" });
  alice.drop();
  await alice.reconnected();
  await t.connect({ player: "carol" });
  expect(t.live.state).toMatchObject({ x: "alice", o: "bob" });

  await t.hibernate();
  await t.connect({ player: "bob" });
  expect(t.live.state).toMatchObject({ x: "alice", o: "bob" });
});

test("chat goes to everyone else", async () => {
  const t = testRoom(room);
  const alice = await t.connect({ player: "alice" });
  const bob = await t.connect({ player: "bob" });
  alice.send({ type: "chat", text: "good luck" });
  await t.settle();
  bob.expectMessage({ type: "chat", from: "alice", text: "good luck" });
  expect(alice.messages).toEqual([]);
});

What has no direct equivalent

Namespaces. IRT has no namespaces. Separate parts of a product that share nothing, such as a game and its admin tools, become separate projects. Kinds of room within one game share one room module, which tells them apart by a room ID prefix you choose, such as duel- and ffa-.

Cross-room messages and global broadcasts. io.emit to every socket, io.to(otherRoom).emit from a handler, serverSideEmit and fetchSockets across rooms have no counterpart. IRT rooms don’t message each other, and a room’s code sees only its own connections. Do it from your backend: it lists rooms with GET /projects/{p}/rooms, sends a message into any room with POST /projects/{p}/rooms/{id}/messages, which the room answers in onRequest, and learns about joins and leaves from webhooks. For something every player sees at once, such as site-wide chat in a small game, every client can also hold a connection to one shared room, up to its room size’s connection limit.

Acks from server to client. The room can’t call a client and wait for its answer. Send a message, and have the client answer with a message or a call.

Many rooms per socket. A Socket.IO socket can be in any number of rooms and receive all their broadcasts over one connection. An IRT connection is to one room. Hold a connection per room, or put the channels into one room, such as one entity per channel with interest deciding who sees which.

Arbitrary events and binary blobs as state. Socket.IO sends whatever you emit. IRT syncs state as typed entities, and messages are JSON or a Uint8Array, at most 64 KB each. Big data, such as a map, goes in bytes fields of chunk entities.

Your own HTTP server. IRT rooms don’t serve HTTP, and a room can’t share an Express app with the socket server. Routes move to your backend, which reaches rooms through the HTTP API; static files move to the project’s site.

Adapters and sticky sessions. There’s nothing to configure. The router sends each connection to the room host running its room, wakes hibernated rooms on connect, and many rooms share a room host.

Checklist

  1. Write schema.ts: each per-room object you kept in a Map becomes state, an entity kind, or private state for what one player alone should see. Import it from both the room and the client.
  2. Move each socket.on handler into onMessage, or into a call if the client waited on an ack. Validate every field.
  3. Delete every emit of state; set entity fields instead. Keep emits of events, such as chat, as room.send and room.broadcast.
  4. Replace socket.id with conn.player wherever you meant the player, such as seats and scores.
  5. Replace setInterval loops with tickRate and onTick. A room with no loop, like this one, leaves tickRate out.
  6. Replace the join event with connect, and room choice with a room ID, createRoom, joinByCode, listPublic or quickJoin.
  7. Move io.use authentication to player tokens your backend signs, or allow guests, and anything that crosses rooms to your backend and the HTTP API.
  8. Write tests with @irtio/testing for each message and call, a dropped connection (drop() and reconnected()), a crash (t.host.crash()) and a hibernation (t.hibernate()). The testing guide has a pattern for each.
  9. Run it with npx irt dev, check rooms in the inspector, then npx irt deploy.