基本上标题是如何从任何路线向前端发射插座?
E.g。说我有路线
route.get("/queue", function(req, res) {
socket.emit("add queue", "username");
});
route.get("/queue/leave", function(req, res) {
socket.emit("leave queue", "username");
});
或者我是否必须在异步回调中执行所有操作?
答案 0 :(得分:0)
将用户的套接字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?');
});
客户方:
socket.emit('register', user_id);