在我的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.
}
如果客户端socket.emit
未触发但由客户端发布/获取触发后发送/获取,快递路由如何访问特定客户端的套接字引用。在路由中定位socket.io server(io/sessionSockets)/client(socket)
对象的最佳方法是什么,以便我可以轻松获得此客户端的套接字引用?
答案 0 :(得分:5)
这三个步骤帮助我解决了问题。这也标识了标签,因为这是我的要求之一。
在连接时,使用socket.id
加入,然后使用
socket.id
发送回客户端
io.sockets.on('connection', function(socket) {
socket.join(socket.id);
socket.emit('server_socket_id', {socket_id : socket.id});
}
客户端使用
接收emit事件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;
});
在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]);
});
答案 1 :(得分:0)
执行此操作的最佳方法是使用socket.io
授权设置,尽管模块session.socket.io
是专门为此目的创建的。每次套接字建立连接时,都会存储握手数据(虽然我听说过flashsockets不会通过浏览器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];
});