NodeJS 如何在express.js应用程序中对多个文件使用套接字io示例

rbpvctlc  于 2023-01-01  发布在  Node.js
关注(0)|答案(3)|浏览(140)

在我用express-generator生成的express应用程序中,我想在其他一些控制器文件中使用socket.ioio来向客户端套接字发送数据。我的方法如下所示,但我得到了以下错误。如果有人能在这种情况下帮助我,那将是一个很大的帮助。
(node:11376)未处理承诺拒绝警告:类型错误:io.emit不是位于F:\backend\controllers\LessonController.js:169:9的函数
express-generator生成的express应用程序中,创建服务器的过程发生在/bin/www.js中,我尝试从那里导入io示例并在其他文件中使用它,但没有成功。

文件夹/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;

课程控制器.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);
                }
            }
        )
    }
};
nukf8bse

nukf8bse1#

您可以尝试将socket.io示例导出到全局级别,并根据需要访问它。
我的项目也是用express-generator创建的,因此,遵循相同的模板。
在我的项目中,我想计算当前主页中的活跃用户数。
下面是一个例子:

    • 斌/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);
    • 服务器/索引. 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

vptzau2j

vptzau2j2#

这里有一个解决方案
创建模块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);
            })
    }
};
mtb9vblg

mtb9vblg3#

创建socketInstance.js

let io = null;

// set this when you initialize the io
const setSocketInstance = (ioInstance) => {
  io = ioInstance;
};
//  you can call this anywhere
const getSocketInstance = () => {
  return io;
};

socket.js内部初始化io

const setSocketInstance = require("./socketInstance");
const initializeIO = (server) => {
  const io = require("socket.io")(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
    },
  });
  // as soon as we initialize the io, we set the instance
  setSocketInstance(io);
 // ....
};

现在,您可以在应用中的任何位置调用getSocketInstance

相关问题