通过多个页面将变量保存在socket.io中 [英] Keeping variables in socket.io through multiple pages
问题描述
我对node.js和socket.io相当陌生,因此其中一些问题似乎真的很愚蠢.话虽如此,我一直在尝试开发一个可以在不同页面之间存储用户名的应用程序.例如,我将用户名设置在一页上.然后,我被重定向到另一个页面,但是我的用户名仍然是在套接字连接中可访问的变量.
I am fairly new to node.js and socket.io, so some of these questions may seem really stupid. With that being said, I have been trying to develop an application which can store an username between different pages. For example, I set my username on one page. I then get redirected to another page, but my username still remains as a variable accessible in the socket connection.
这是我的基本服务器设置:
Here is my basic server setup:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/set', function(req, res){
res.sendfile('set.html');
});
app.get('/get', function(req, res){
res.sendfile('get.html');
});
io.on('connection', function(socket){
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
我的问题是:
1.)可以知道套接字当前在哪个页面上?如果是这样,怎么办?
1.) It is possible to know what page the socket is currently on? If so, how?
2.)如何与io.on(...)中的信息进行交互?
2.) How can I interact with that information in the io.on(...)?
我曾尝试将会话中间件用于socket.io和express,但似乎无法正常工作.我很确定使用会话是实现此目的的最佳方法,但是我不知道如何实现它们.关于设置可通过不同页面访问的会话的任何建议也将很好.
I have tried using session middleware for socket.io and express, but I can't seem to get any to work. I'm pretty sure that using sessions is the best method for this, but I don't know how to implement them. Any suggestions about setting up a sessions accessible through different pages would be nice as well.
谢谢!
推荐答案
您必须为此使用快速会话和握手:
You have to use express sessions and handshake for it:
sock.on('your_socket_name', function (data) {
sock.handhsake.session.name = data.name;
sock.handshake.session.save();
});
通过此链接,它将一定会对您有所帮助:
go through this link, it will sure help you:
https://www.npmjs.com/package/socket.io-handshake
这篇关于通过多个页面将变量保存在socket.io中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!