从另一个文件访问SocketIO

问题描述 投票:0回答:3

我正在尝试向从单独文件连接的所有套接字发射。但我似乎无法弄明白。

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解析为新闻函数或将我的函数移动到套接字文件?

javascript node.js socket.io
3个回答
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

希望现在对你有意义。


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

0
投票

我设法通过改变module.exports的位置来解决这个问题。我在初始化socket变量之后立即把它放了,因为它是我输出它的唯一的东西。

© www.soinside.com 2019 - 2024. All rights reserved.