nodejs新手。在nodejs中PHP的session_start()相当于什么?

时间:2015-07-14 14:24:00

标签: javascript node.js sockets session

我想生成一个会话ID,但它对浏览器是唯一的,而不是每个标签。

我能找到的就是这种类型的东西>>

http://blog.modulus.io/nodejs-and-express-sessions

演示了如何使用会话来存储数据,但它在每个选项卡中都受到限制,最终会有一个新会话。我正在寻找的是,浏览器获得一个唯一的会话ID,它自动生成并可从其他选项卡访问。现在试图远离浏览器存储,直到它已经成熟到大多数用户拥有该功能的程度。由于我们仍然有相当多的用户使用不支持本地存储的旧浏览器,因此随机会话ID是理想的。

我使用这个唯一ID作为私人'房间',聊天程序的用户将加入该房间以获得支持。每个用户都在自己的私人房间,但可以跨选项卡访问同一个房间。我知道它有点草率,但从nodejs的初学者的角度来看,使用一些独特的键来处理浏览器实例要比处理交叉标签套接字打开/关闭检测等要简单得多。我实现了使用这种方法,每个标签将它自己的套接字连接到服务器,我现在可以 - 现在。

我已经尝试了以下(我认为它会使用套接字会话,而不是浏览器会话,即使它确实有效),但这不起作用(对于经验丰富,为什么这不起作用的人可能很明显

客户端

socket.on('connect', function() {
    socket.emit('set room', this.socket.sessionid);
})

服务器

socket.on('set room', function(room) {
    socket.join(room);
    console.log('joined : ' + room);
});

这是一个简单的脚本示例,并且使用为使用express-sessions提供的答案发生了什么。它在socket.io上运行得不好,或者出现了严重错误:

(删除会话的app.use(function.....),因为它导致客户端永远不会到达套接字连接。

app.js

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    session = require('express-session');

var settings = require('./settings.json');

server.listen(settings.port);

app.use(session({
    secret: settings.secret,
    resave: false,
    saveUninitialized: true
}));

//app.use(function(req, res, next) {
//  var sess = req.session;
//  if(!sess.id) {
//      sess.id = sess.sessionID;
//  }
//});

app.get('/', function(request, response){
    validateHost('index.html', request, response);
});

io.sockets.on('connection', function(socket){


    socket.on('send message', function(data){
        //io.sockets.emit('new message', data);
        console.log(session.sessionID);
        io.sockets.emit('new message', 'session:' + session.sessionID);
        socket.broadcast.to(socket.room).emit('new message', data);
    });

    socket.on('set room', function(room) {
        socket.join(room);
        console.log('joined : ' + room);
    });

    socket.on('disconnect', function(){
        console.log('user disconnected');
    });

});

function validateHost(file, request, response) {
    var hostname = ( request.headers.host.match(/:/g) ) ? request.headers.host.slice( 0, request.headers.host.indexOf(":") ) : request.headers.host;
//  var file = 'index.html';

    if(settings.hosts.indexOf(hostname)) {
        response.sendFile(__dirname + '/' + file);
    } else {
        response.statusCode = 404;
        response.write('Access Denied to ' + request.headers.host + ' ' + file);
        response.end();
    }
}

的index.html

<html>
<head>
    <title>Realtime Private Chat</title>
    <style>
        #chat { height: 200px; width: 300px; overflow-y: auto; overflow-x: hidden; }
        #chat p { width: 270px; }

        .commentArea {
            font: 14px Arial;
            padding: 0 10px;
            margin-top: 20px;    
        }

        .bubbledLeft,.bubbledRight {
            margin-top: 20px;
            padding: 5px 9px;
            max-width: 50%;
            clear: both;
            position: relative;
        }

        .bubbledLeft{
            float: left;
            margin-right: auto;
            -webkit-border-radius: 8px 8px 8px 0px;
            -moz-border-radius: 8px 8px 8px 0px;
            -o-border-radius: 8px 8px 8px 0px;
            -ms-border-radius: 8px 8px 8px 0px;
            border-radius: 8px 8px 8px 0px;
            background-color: #65B045;
            color: #ffffff;
        }

        .bubbledLeft:before {
            border-bottom: 10px solid #65B045;
            border-left: 9px solid rgba(0, 0, 0, 0);
            position: absolute;
            bottom: 0;
            left: -8px;
            content: "";
        }

        .bubbledRight{
            float: right;
            margin-left: auto;
            text-align: right;
            -webkit-border-radius: 8px 8px 0px 8px;
            -moz-border-radius: 8px 8px 0px 8px;
            -o-border-radius: 8px 8px 0px 8px;
            -ms-border-radius: 8px 8px 0px 8px;
            border-radius: 8px 8px 0px 8px;
            background-color: #07D;
            color: white;
        }

        .bubbledRight:before {
            border-bottom: 9px solid #07D;
            border-right: 9px solid rgba(0, 0, 0, 0);
            position: absolute;
            bottom: 0;
            right: -8px;
            content: "";
        }

    </style>
</head>
<body>
    <div id="chat"></div>

    <form id="send-message">
        <input id="message" type="text" />
        <button type="submit">Send</button>
    </form>
</body>
<script src="//code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>

<script>
    jQuery(function($) {
        var socket = io.connect();
        var sendmessage = $('#send-message');
        var sendmessagetext = $('#message');
        var chat = $('#chat');

        sendmessage.submit(function(e) {
            e.preventDefault();
            socket.emit('send message', sendmessagetext.val());
            chat.append('<div class="bubbledRight">' + sendmessagetext.val() + '</div>');
            sendmessagetext.val('');
        })

        socket.on('connect', function() {
            //socket.emit('set room', this.socket.sessionid);
        })

        socket.on('new message', function(data) {
            chat.append('<div class="bubbledLeft">' + data + '</div>');
            chat.scrollTop(chat[0].scrollHeight)
//          console.log(data);
        });

    });

</script>

</html>

的package.json

{
    "name": "livechat",
    "version": "1.0.0",
    "description": "Realtime Private Chat Server",
    "main": "app.js",
    "private": "true",
    "author": "",
    "license": "ISC",
    "dependencies":{
        "socket.io":"1.3.5",
        "mysql":"2.8.0",
        "express":"4.13.1",
        "express-session":"1.11.3"
    }
}

settings.json

{
    "port":"3000",
    "hosts":[
            "127.0.0.1",
            "example.com"
        ],
    "secret":"faskjhfuwjhfjas"
}

当试图在socket中的任何地方读取会话时,我得到'undefined'。

1 个答案:

答案 0 :(得分:1)

您将使用快速会话和socket.io的新实现,将两者结合在一起! https://www.npmjs.com/package/express-socket.io-session

<强>的package.json

添加依赖项

"socket.io" : "*",
"express-session" : "*",
"express-socket.io-session" : "*"

<强> App.js

为会话数据添加其他编码

var server  = require("http").createServer(app),
    io = require("socket.io")(server),
    session = require("express-session")({
    secret: "my-secret",
    resave: true,
    saveUninitialized: true
  }),
  sharedsession = require("express-socket.io-session");


// Attach session
app.use(session);

// Share session with io sockets

io.use(sharedsession(session));

io.on("connection", function(socket) {
    // Accept a login event with user's data
        console.log(session.id);
    socket.on("login", function(userdata) {
        socket.handshake.session.userdata = userdata;
    });
    socket.on("logout", function(userdata) {
        if (socket.handshake.session.userdata) {
            delete socket.handshake.session.userdata;
        }
    });        
});