What's the correct way to pass a Socket.IO soc

2019-05-06 16:20发布

At the moment I have a getter/setter socket module as follows

var socket;

module.exports.getSocket = getSocket;
module.exports.setSocket = setSocket;

function getSocket() {
    return socket;
}
function setSocket(sock) {
    if (undefined == socket) socket = sock;
}

In app.js I set as follows

var sio = require('./lib/socket');
var io = require('socket.io').listen(app);
io.sockets.on('connection', function (socket) {
    sio.setSocket(socket);
});

In my module I use as follows

sio = require('./lib/socket');
socket.getSocket().broadcast.emit(...);

It seems a bit contrived is there a better way to do this?

Edit: I would like a general solution to the problem of firing off a message which is not initiated by the client socket. For example suppose I retrieve stock prices from an external source and wish to fire an event on price update. Since it is not client initiated, how can I get access to the socket? Or alternatively let's say I wish to fire off a socket message in response to a POST request. Once again I'm not sure how I would access the socket.

1条回答
Ridiculous、
2楼-- · 2019-05-06 17:13

There are a number of options for sharing the socket, but it would help to know more about what your module is going to do. Without knowing more, I would recommend you just pass the socket to the module via the function you are calling instead of trying to use some shared state.

If you need to use a shared state (you're trying to send messages to specific users triggered by something other than a socket message) then I would recommend sticking with an established session framework and just persist the socket id. You can get the correct socket just using the id.

See this answer for how to use socket.io with sessions: socket.io and session?

Add some more details and I'll revise my answer.

UPDATE

If you are just trying to broadcast to everyone who is connected, you do not need a socket handle. From any module that references socket.io, you can call io.sockets.emit('stuff').

查看更多
登录 后发表回答