跳至主要内容
版本: 4.x

适配器

适配器是服务器端组件,负责将事件广播到所有或部分客户端。

当扩展到多个 Socket.IO 服务器时,您需要用其他实现替换默认的内存中适配器,以便事件正确路由到所有客户端。

以下是我们团队维护的适配器列表

还有其他一些由(很棒的!)社区维护的选项

请注意,在使用多个 Socket.IO 服务器和 HTTP 长轮询时,仍然需要启用粘性会话。更多信息 这里.

API

您可以使用以下方法访问适配器实例

// main namespace
const mainAdapter = io.of("/").adapter; // WARNING! io.adapter() will not work
// custom namespace
const adminAdapter = io.of("/admin").adapter;

socket.io@3.1.0 开始,每个适配器实例都会发出以下事件

  • create-room (参数: room)
  • delete-room (参数: room)
  • join-room (参数: room, id)
  • leave-room (参数: room, id)

示例

io.of("/").adapter.on("create-room", (room) => {
console.log(`room ${room} was created`);
});

io.of("/").adapter.on("join-room", (room, id) => {
console.log(`socket ${id} has joined room ${room}`);
});

发射器

大多数适配器实现都带有其关联的发射器包,该包允许从另一个 Node.js 进程与 Socket.IO 服务器组进行通信。

Emitter diagramEmitter diagram

这在微服务设置中可能很有用,例如,所有客户端都连接到微服务 M1,而微服务 M2 使用发射器广播数据包(单向通信)。

发射器速查表

// to all clients
emitter.emit(/* ... */);

// to all clients in "room1"
emitter.to("room1").emit(/* ... */);

// to all clients in "room1" except those in "room2"
emitter.to("room1").except("room2").emit(/* ... */);

const adminEmitter = emitter.of("/admin");

// to all clients in the "admin" namespace
adminEmitter.emit(/* ... */);

// to all clients in the "admin" namespace and in the "room1" room
adminEmitter.to("room1").emit(/* ... */);

发射器还支持在 socket.io@4.0.0 中添加的实用程序方法

  • socketsJoin()
// make all Socket instances join the "room1" room
emitter.socketsJoin("room1");

// make all Socket instances of the "admin" namespace in the "room1" room join the "room2" room
emitter.of("/admin").in("room1").socketsJoin("room2");
  • socketsLeave()
// make all Socket instances leave the "room1" room
emitter.socketsLeave("room1");

// make all Socket instances in the "room1" room leave the "room2" and "room3" rooms
emitter.in("room1").socketsLeave(["room2", "room3"]);

// make all Socket instances in the "room1" room of the "admin" namespace leave the "room2" room
emitter.of("/admin").in("room1").socketsLeave("room2");
  • disconnectSockets()
// make all Socket instances disconnect
emitter.disconnectSockets();

// make all Socket instances in the "room1" room disconnect (and discard the low-level connection)
emitter.in("room1").disconnectSockets(true);

// make all Socket instances in the "room1" room of the "admin" namespace disconnect
emitter.of("/admin").in("room1").disconnectSockets();

// this also works with a single socket ID
emitter.of("/admin").in(theSocketId).disconnectSockets();
  • serverSideEmit()
// emit an event to all the Socket.IO servers of the cluster
emitter.serverSideEmit("hello", "world");

// Socket.IO server (server-side)
io.on("hello", (arg) => {
console.log(arg); // prints "world"
});