且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在express.js应用程序中的多个文件上使用套接字io实例

更新时间:2023-10-18 10:03:28

您可以尝试将 socket.io 实例导出到全局级别,并根据需要进行访问.

You can try to export the socket.io instance to the global level and access that as needed.

我的项目也是用express-generator创建的,因此遵循相同的模板.

My project was also created with express-generator, therefore, follows the same template.

在我的项目中,我想计算主页中当前的活动用户数.

In my project, I would like to count the current number of active users in home page.

这里是一个例子:

bin/www

#!/usr/bin/env node
const app = require('../app');
const http = require('http').Server(app);
const io = require('socket.io')(http)
http.listen(process.env.PORT);
io.on('connection', (socket) => {    
    const qtd = socket.client.conn.server.clientsCount;
    io.emit('novaconexao', qtd);
    socket.on('disconnect', () => {
        io.emit('disconnecteduser', qtd - 1);
    });
});
app.set('socketio', io);//here you export my socket.io to a global       

console.log('Microsservice login listening at http://localhost:%s', process.env.PORT);

server/index.js

const router = require('express').Router();
router.get('/', (req, res) => {
    const io = req.app.get('socketio'); //Here you use the exported socketio module
    console.log(io.client.conn.server.clientsCount)
    io.emit('new-user', {qtd: io.client.conn.server.clientsCount})
    res.status(200).json({ msg: 'server up and running' });
})
module.exports = router;

按照此策略,您可以在应用程序中的任何路由中使用 socketio .

Following this strategy, you can use socketio in any route in your application.