我对 Web 开发有点陌生,尤其是在 Node 领域,而且我在使用 socket.io 方面遇到了困难。 问题是我需要将“io”导出到其他文件中才能发出消息,但它不起作用,因为我可能以错误的方式执行此操作。
我尝试了许多 stackOverflow 解决方案,但没有成功。
这两个文件是server.js,其中是socket的配置:
let server = http.createServer(app);
let io_fin=io_test.listen(server);
module.exports= io_test;
在同一个文件中,我的“发出请求”正在运行:
io_fin.on('connection', function(socket){
console.log('an user connected');
socket.emit('chat message', 'TESTING');
});
在另一个文件中,我导入了以下内容:
let yoyo = require('socket.io');
我尝试像这样发出:
yoyo.emit('chat message', 'TEST2');
API 崩溃并提示“yoyo.emit 不是函数”。
我尝试了很多不同的方法来导出它,例如:
module.exports= io_test(server);
module.exports=io_fin;
module.exports= io_test.listen(server);
等等..
我觉得我错过了套接字的一个关键概念,因为我完全陷入困境! 很抱歉这个“新手”问题,但我觉得我真的需要一些帮助。 提前致谢。
最佳答案
let yoyo = require('socket.io')
此行需要一个新的 socket.io
函数。 p>
您正在 server.js
中导出,因此您应该从该文件导入,如下所示:
// assuming the file you're importing from is in the same folder as server.js
let yoyo = require('./server');
关于node.js - 如何在项目的其他文件上导出Socket.io实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55711504/