Skip to main content

如何注册全局中间件

¥How to register a global middleware

在 Socket.IO v2 中,为主命名空间注册的中间件将充当全局中间件,应用于所有命名空间,因为客户端将首先连接到主命名空间,然后连接到自定义命名空间:

¥In Socket.IO v2, a middleware that was registered for the main namespace would act as a global middleware, applying to all namespaces, since a client would first connect to the main namespace, and then to the custom namespace:

// Socket.IO v2

io.use((socket, next) => {
// always triggered, even if the client tries to reach the custom namespace
next();
});

io.of("/my-custom-namespace").use((socket, next) => {
// triggered after the global middleware
next();
});

从 Socket.IO v3 开始,情况不再如此:仅当客户端尝试访问主命名空间时才会调用附加到主命名空间的中间件:

¥This is not the case any more starting with Socket.IO v3: a middleware attached to the main namespace is only called when a client tries to reach the main namespace:

// Socket.IO v3 and above

io.use((socket, next) => {
// only triggered when the client tries to reach the main namespace
next();
});

io.of("/my-custom-namespace").use((socket, next) => {
// only triggered when the client tries to reach this custom namespace
next();
});

要在较新版本中创建全局中间件,你需要将中间件附加到所有命名空间:

¥To create a global middleware in newer versions, you need to attach your middleware to all namespaces:

  • 手动:

    ¥either manually:

const myGlobalMiddleware = (socket, next) => {
next();
}

io.use(myGlobalMiddleware);
io.of("/my-custom-namespace").use(myGlobalMiddleware);
const myGlobalMiddleware = (socket, next) => {
next();
}

io.use(myGlobalMiddleware);

io.on("new_namespace", (namespace) => {
namespace.use(myGlobalMiddleware);
});

// and then declare the namespaces
io.of("/my-custom-namespace");
caution

new_namespace 监听器之前注册的命名空间不会受到影响。

¥The namespaces that are registered before the new_namespace listener won't be affected.

const myGlobalMiddleware = (socket, next) => {
next();
}

io.use(myGlobalMiddleware);

const parentNamespace = io.of(/^\/dynamic-\d+$/);

parentNamespace.use(myGlobalMiddleware);
caution

现有命名空间始终优先于动态命名空间。例如:

¥Existing namespaces always have priority over dynamic namespaces. For example:

io.of("/admin");

io.of(/.*/).use((socket, next) => {
// won't be called for the main namespace nor for the "/admin" namespace
next();
});

有关的:

¥Related: