Socket.IO中间件io.use [英] Socket.IO middleware, io.use

查看:332
本文介绍了Socket.IO中间件io.use的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个基于expressJS和Socket.io构建的Web应用程序上工作. 在以下文章中,我看到了中间件语法的用法,这对我来说是新的.这是语法示例:

Working on a web application which is built upon expressJS and Socket.io. In the following post I saw the usage of middleware syntax which was new to me. Here is an example of the syntax:

const io = require('socket.io')();

io.use(function(socket, next) {
  // execute some code
  next();
})
.on('connection', function(socket) {
    // Connection now authenticated to receive further events

    socket.on('message', function(message) {
        io.emit('message', message);
    });
});

它基本上在socket.io实例上使用中间件功能.我以前的理解是,中间件软件只能在快速实例(app.use(...))上使用.

It basically uses middleware functions on the socket.io instance. My previous understanding was that middlware can only be used on the express instance (app.use(...)).

  1. 此语法是否只是与app.use(...)类似的常规中间件?
  2. 如果不同,有什么区别?
  1. Is this syntax just regular middleware which works similarly to app.use(...)?
  2. If it is different, what are the differences?

推荐答案

io.use()允许您指定一个为每个新的传入socket.io连接调用的函数.它可以用于各种各样的事情,例如:

io.use() allows you to specify a function that is called for every new, incoming socket.io connection. It can be used for a wide variety of things such as:

  1. 记录
  2. 身份验证
  3. 管理会话
  4. 费率限制
  5. 连接验证

依此类推...

其目的类似于Express中间件(例如app.use()),但这是用于传入的socket.io连接,而不是传入Express管理的常规http请求.如果要中间件处理传入的http请求,请将Express中间件与app.use()一起使用.如果您希望中间件处理传入的socket.io连接,请在io.use()中使用socket.io中间件.

It's purpose is similar to Express middleware (like with app.use()), but this is for incoming socket.io connections, not incoming the regular http requests that Express manages. If you want middleware to process an incoming http request, use Express middleware with app.use(). If you want middleware to process an incoming socket.io connection, use socket.io middleware with io.use().

这篇关于Socket.IO中间件io.use的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆