如何在连接回调之外的应用程序中的任何位置发出套接字?

时间:2021-10-30 19:37:18

Basically as the title says how can I emit sockets to the front end from any route?

基本上标题说我如何从任何路线向前端发射插座?

E.g. Say I have a route

例如。说我有路线

route.get("/queue", function(req, res) {
    socket.emit("add queue", "username");
});

route.get("/queue/leave", function(req, res) {
    socket.emit("leave queue", "username");
});

Or do I have to do everything from within the asynchronous callback?

或者我必须在异步回调中做所有事情?

1 个解决方案

#1


Store the user's socket id in their session or a global, this should demonstrate the basic idea:

将用户的套接字ID存储在其会话或全局中,这应该说明基本思路:

var io = require('socket.io');
var users = {};

io.on('connection', function(socket) {
   io.on('register', function(user) {
      users[user] = socket.id;
   });
});

route.get('/login', function(req, res) {
  ...
  req.session.user_id = user_id;
});

route.get("/queue/leave", function(req, res) {
   var socketId = users[req.session.user_id];
   io.sockets.connected[socketId].emit('alert', 'whatup?');
});

Client side:

socket.emit('register', user_id);

#1


Store the user's socket id in their session or a global, this should demonstrate the basic idea:

将用户的套接字ID存储在其会话或全局中,这应该说明基本思路:

var io = require('socket.io');
var users = {};

io.on('connection', function(socket) {
   io.on('register', function(user) {
      users[user] = socket.id;
   });
});

route.get('/login', function(req, res) {
  ...
  req.session.user_id = user_id;
});

route.get("/queue/leave", function(req, res) {
   var socketId = users[req.session.user_id];
   io.sockets.connected[socketId].emit('alert', 'whatup?');
});

Client side:

socket.emit('register', user_id);