我使用带有套接字的node.js,但是如何从我的会话中获取用户名?
当我只使用express和socket的包时,这是否可行?
当我进入登录页面时,我可以选择用户名。当我点击登录时,我在会话中推送我的用户名。这很好用。但是如何在我的io.on(“连接”)中使用此会话?
由于
亲切的问候约翰
var express = require("express");
var app = express();
var http = require("http").createServer(app);
var session = require("express-session");
var io = require("socket.io")(http);
var bodyparser = require("body-parser");
app.set("view engine","ejs");
app.use(express.static(__dirname + "/public"));
app.use(bodyparser.urlencoded(true));
app.use(session({secret: "abc"}));
var serverSocket = io.listen(8060);
var users = [];
app.get("/",function (req, res) {
if(req.session.username === undefined)
{
res.render("login",{error:null});
}
else
{
res.redirect("/chat");
}
});
app.post("/login",function (req, res) {
var username = req.body.username;
var index = users.indexOf(username);
console.log(index);
if(index === -1)
{
users.push(username);
req.session.username = username;
res.redirect("/chat");
}
else
{
res.render("login",{logedIn: true,error: "gebruiker bestaat al"});
}
});
app.get("/chat",function (req,res) {
if(req.session.username === undefined)
{
res.render("login",{error:"u moet ingelogd zijn"});
}
else {
res.render("chat");
}
});
io.on("connection",function (socket) {
socket.username = session.username;
var username = socket.username;
socket.emit("connected",{username : session.username});
socket.on("messageSend",function (data) {
socket.emit("messageSend",{username : username,message:data.message});
});
socket.on("disconnect",function () {
socket.username = null;
console.log("diconnected");
});
});
var server = http.listen(8050,function () {
console.log(server.address().port);
});
答案 0 :(得分:1)
socket.io-express-session library。这是一个非常简单的库,它是socket.io的包装器。它只是在握手期间获取会话信息,然后将其传递给socket.io的连接函数。您可以通过连接侦听器中的socket.handshake.session访问会话。
//instead of
io.sockets.on('connection', function (socket) {
//do pubsub here
...
})
var socketIOExpressSession = require('socket.io-express-session');
io.use(socketIOExpressSession(app.session)); // session support
//But with sessions.sockets.io, you'll get session info
/*
Use SessionSockets so that we can exchange (set/get) user data b/w sockets and http sessions
Pass 'jsessionid' (custom) cookie name that we are using to make use of Sticky sessions.
*/
var SessionSockets = require('session.socket.io');
var sessionSockets = new SessionSockets(io, sessionStore, cookieParser, 'jsessionid');
io.on('connection', function (socket) {
//get info from session
var user = socket.handshake.session.user;
//Close socket if user is not logged in
if (!user)
socket.close();
//do pubsub
socket.emit('chat', {user: user, msg: 'logged in'});
...
});