如何在express.js应用程序中的多个文件上使用套接字io实例 [英] How to use socket io instance on multiple files in express.js app

查看:50
本文介绍了如何在express.js应用程序中的多个文件上使用套接字io实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Express应用程序(由 express-generator 生成)中,我想在其他一些控制器文件中使用 socket.io io 向客户端套接字发送数据.我的方法如下,但是我得到以下错误.如果有人可以在这种情况下为我提供帮助,那将是一个很大的帮助.

In my express app, generated with express-generator, I want to use the io of socket.io in some other controller files to emit data to client sockets. My approach is below, but I get the following error with that. It would be a great favor if someone can help me in this case.

(节点:11376)UnhandledPromiseRejectionWarning:TypeError:io.emit不是一个函数在F:\ backend \ controllers \ LessonController.js:169:9

(node:11376) UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function at F:\backend\controllers\LessonController.js:169:9

在由 express-generator 生成的Express应用程序中,创建服务器的过程发生在/bin/www.js 中.我尝试从那里导入 io 实例,并在其他文件中使用它,但是它不起作用.

In the express apps, generated by express-generator, the process of creating the server happens in the /bin/www.js. I tried importing the io instance from there and use it in some other file, but it didn't work.

bin/www.js

#!/usr/bin/env node

var app = require('../app');
var debug = require('debug')('backend:server');
var http = require('http');

var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);

var server = http.createServer(app);
const io = require('socket.io')(server);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

// several other functions are omitted for brevity

module.exports = io;

LessonController.js

const Lesson = require('../models/Lesson');
const Course = require('../models/Course');
const User = require('../models/User');
const io = require('../bin/www')
var _ = require('lodash');

module.exports = {
    addComment: async (lessonId, userId, content, callback) => {
        const newData = {
            comments: {
                user: userId,
                content: content,
            },
        };

        Lesson.findOneAndUpdate({ _id: lessonId }, { $push: newData }, {new: true})
        .exec()
        .then(
            function (data) {
                if (data) {
                    io.emit("comment_"+lessonId,data)
                    callback(null, data);
                } else if (err) {
                    callback(err, null);
                }
            }
        )
    }
};

推荐答案

您可以尝试将 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.

这篇关于如何在express.js应用程序中的多个文件上使用套接字io实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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