2

在我的 app.js 我有

var app = express();
var serv = http.createServer(app);
var io = require('socket.io').listen(serv);
io.sockets.on('connection', function(socket) {
   //some code here
}

var SessionSockets = require('session.socket.io'),
    sessionSockets = new SessionSockets(io, express_store, cookieParser);
sessionSockets.on('connection', function (err, socket, session) {
   //set up some socket handlers here for the specific client  that are 
   //only called when a client does a socket.emit. 
   //These handlers have access to io, sessionSockets, socket, session objects.
}

在处理不是由客户端触发而是由客户端 post/get 触发的 post/get 之后,快速路由如何访问特定客户端的套接字引用socket.emit。确定路由中对象范围的最佳方法是什么,socket.io server(io/sessionSockets)/client(socket)以便我可以轻松获取客户端的套接字引用?

4

2 回答 2

5

这三个步骤帮助我解决了问题。这也唯一地标识了选项卡,因为这是我的要求之一。

  1. 在连接时,加入使用socket.id,然后使用发送socket.id回客户端

    io.sockets.on('connection', function(socket) {
      socket.join(socket.id);   
      socket.emit('server_socket_id', {socket_id : socket.id});
    }
    
  2. 客户端使用接收发出事件

    socket.on('server_socket_id', function(data){
      //assign some global here which can be sent back to the server whenever required.
      server_socket_id = data.socket_id;
    });
    
  3. app.js我这样获取相应的套接字并将其传递给路由。

    app.post('/update', function(req, res){
      var socket_id = req.body.socket_id;
      route.update(req, res, io.sockets.in(socket_id).sockets[socket_id]);
    });
    
于 2013-09-04T07:03:12.937 回答
0

最好的方法是使用socket.io授权设置,尽管该模块session.socket.io是专门为此目的而创建的。每次套接字建立连接时,都会存储握手数据(尽管我听说闪存套接字不会传递浏览器 cookie)。这就是它的样子(并且类似地写在您正在使用的模块中):

io.configure(function () {
  io.set('authorization', function (handshakeData, callback) {
    //error object, then boolean that allows/denies the auth
    callback(null, true);
  });
});

您可以从这里做的是解析 cookie,然后通过 cookie 名称存储对该套接字的引用。因此,您可以将其添加到授权设置中:

var data = handshakeData;
if (data.headers.cookie) {
  //note that this is done differently if using signed cookies
  data.cookie = parseCookie(data.headers.cookie);
  data.sessionID = data.cookie['express.sid'];
}

然后,当您侦听连接时,按会话标识符存储客户端:

var clients = {};
io.sockets.on('connection', function(socket) {
  //store the reference based on session ID
  clients[socket.handshake.sessionID] = socket;
});

当你在 Express 中收到一个 HTTP 请求时,你可以像这样获取它:

app.get('/', function(req, res) {
  //I've currently forgotten how to get session ID from request,
  //will go find after returning from school
  var socket = clients[sessionID];
});
于 2013-09-03T14:44:57.110 回答