我正在尝试发出从单独文件连接的所有套接字。但是我似乎无法弄清楚。
Socket.js
var socketio = require('socket.io');
var users = require('./modules/users');
var io = socketio();
socket.io = io;
io.on('connection', function(socket){
//Stuff
console.log('Hello :)');
});
module.exports = socket;
Users.js
var socket = require('../socket');
function news(){
socket.io.sockets.emit('news', {
message: 'Woah! Thats new :)'
})
}
setInterval(function(){
news();
}, 5 * 1000);
但是,users.js中的socket
似乎是空的,我似乎无法访问io对象。我该如何做才能将其发布给所有用户?无需将io.sockets解析为新闻功能或将我的功能移至套接字文件?
答案 0 :(得分:2)
您可以使用 let 定义 io 对象作为 utils 和 io 函数中的全局变量。您可以从任何文件调用这些函数。例如:
git reflog
// app.js
const { socketConnection } = require('./utils/socket-io');
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
socketConnection(server);
// utils/socket-io
let io;
exports.socketConnection = (server) => {
io = require('socket.io')(server);
io.on('connection', (socket) => {
console.info(`Client connected [id=${socket.id}]`);
socket.join(socket.request._query.id);
socket.on('disconnect', () => {
console.info(`Client disconnected [id=${socket.id}]`);
});
});
};
exports.sendMessage = (roomId, key, message) => io.to(roomId).emit(key, message);
exports.getRooms = () => io.sockets.adapter.rooms;
答案 1 :(得分:0)
Users.js
exports = module.exports = function(io){
io.sockets.on('connection', function (socket) {
socket.on('news', {
message: 'Woah! Thats new :)'
})
});
}
App.js
const app = require('http').createServer(handler)
const io = require('socket.io').listen(app)
const Users = require('./modules/users')(io)
// const anotherModule = require('./modules/anotherModule')(io)
// const andSoOn = require('./modules/andSoOn')(io)
// and emit it here
setInterval(function(){
io.emit('news')
}, 5 * 1000);
// you can expose the io object to other files
exports.io = io
希望现在对您有意义。
答案 2 :(得分:0)
只需创建一个socket service
对象,该服务对象仅发布一些helper
函数。
您的案例示例:
// Socket.js
var socketio = require('socket.io');
var users = require('./modules/users');
var io = socketio();
socket.io = io;
io.on('connection', function (socket) {
//Stuff
console.log('Hello :)');
});
var toAll = function (eventName, data) {
io.sockets.emit(event, data);
}
module.exports = {
toAll: toAll // publish `toAll` function to call every where
};
// Users.js
var socketService = require('../socket');
function news() {
socketService.toAll('news', {
message: 'Woah! Thats new :)'
});
}
setInterval(function () {
news();
}, 5 * 1000);
答案 3 :(得分:0)
我设法通过更改module.exports
的位置来解决此问题。初始化socket
变量后,我立即放了它,因为这是我导出的唯一东西。