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

时间:2020-05-05 08:10:08

标签: node.js express socket.io

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

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

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

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);
                }
            }
        )
    }
};

2 个答案:

答案 0 :(得分:1)

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

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

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

这里是一个例子:

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

答案 1 :(得分:0)

这是一个解决方案

创建一个模块 io.js

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

let io = null;
module.exports = {
    //Initialize the socket server
    initialize: function(httpServer) {
        io = sio(httpServer);
        io.on('connection', function(socket) {
            console.log('New client connected with id = ', socket.id);
            socket.on('disconnect', function(reason) {
                console.log('A client disconnected with id = ', socket.id, " reason ==> ", reason);
            });
        });

    },
    //return the io instance
    getInstance: function() {
        return io;
    }
}

bin / www.js

var server = http.createServer(app);
require('path_to_io_js/io').initialize(server);

在您的控制器/ LessonController.js中

//require the io module
const socket = require('path_to_io_js/io');
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) {
                    //get the io instance
                    const io = socket.getInstance();
                    io.emit("comment_" + lessonId, data)
                }
                callback(null, data);
            }).catch(err => {
                callback(err);
            })
    }
};