session.socket.io错误:无法按键查找会话:connect.sid

时间:2013-12-26 05:08:47

标签: javascript node.js session express socket.io

好的。所以这件事在过去两天一直困扰着我。所以我决定与你们分享整个代码,以找出我失踪的东西。除了stackoverflow中的所有其他类似问题之外,我已经阅读了this issue中的所有注释,但我还是找不到解决方案。这是我的服务器:

var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var connect = require('connect');
var redis = require('redis');
var crypto = require('crypto');

var app = express();

var server = http.createServer(app);
var io = require('socket.io').listen(server);

// Redis Client for saving sessions
var rClient = redis.createClient();

// Redis Client Used to store user Information
var redisUsersClient = redis.createClient();
const userDB = require('redis-user')(redisUsersClient);

// Session Tracking
 var cookieParser = express.cookieParser();
 console.log(cookieParser);
var RadisStore = require('connect-redis')(express);
var sessionStore = new RadisStore({
                            host: '127.0.0.1',
                            port: 6379,
                            db: 10
                        });

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(cookieParser);
app.use(express.session({ store: sessionStore,
                                                    secret: 'SEKR37',
                                                    cookie: { path: '/', httpOnly: true, maxAge: null }
                                                }));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// Create socket connection with session using "session.socket.io" module
var SessionSockets = require('session.socket.io')
, sessionSockets = new SessionSockets(io, sessionStore, cookieParser);

var clients = {};

sessionSockets.on('connection', function (err, socket, session) {
    console.log(err);
    //console.log(socket.handshake);

  socket.emit('welcome', {username: session.user});

    socket.on('add-user',function(data){
        console.log(data.username);
        clients.username = data.username;
        //console.log(clients);

        // emit to all other users that the user is connected
        socket.broadcast.emit('entrance', data.username + ' has connected');

        // emit to all other users to update their users list
        io.sockets.emit('add-user',{clients:clients});
    });

        // on disconnect update the user list
        socket.on('disconnect', function(){
            delete clients[session.user];
            io.sockets.emit('add-user',{clients:clients})
        });

});

app.get('/', function(req, res){
    if(!req.session.user)
        res.redirect('/login')
    else {
        res.sendfile('chat.html')
    }
});
app.get('/login', function(req, res){
        res.render('login');
});
app.get('/register', function(req, res){
        res.render('register');
});

app.get('/logout', function(req, res){
        req.session.destroy();
        res.redirect('/login');

});

app.post('/login',function(req, res){
        var password = require('crypto').createHash('sha1WithRSAEncryption').update(req.body.password).digest('utf8');
        var username = req.body.username+"@mychat.com";
        //console.log(req.session);
        userDB.validateUser(username, password, function(result){
            if(result)
            {
                    req.session.user = username;
                    req.session.status = 1;
                    req.session.save();

                    res.redirect('/');

                //res.send("hell's yeah");
            }
            else
            {
                res.send("Wrong Credential. Please <a href='/login'>Try Again</a>");
            }
        });
});
app.post('/register',function(req, res){

        var username = req.body.username + "@mychat.com";
        var password = require('crypto').createHash('sha1WithRSAEncryption').update(req.body.password).digest('utf8');
        var verify = require('crypto').createHash('sha1WithRSAEncryption').update(req.body.verify).digest('utf8');
        if(password==verify)
        {
            userDB.createUser(username, password, function(result) {
                if (result) {
                    /* continue */
                            redisUsersClient.hset('users', username, password);
                            res.redirect('/');
                } else {
                    /* show error */
                    res.send("could not create user, Something very unexpected happened");
                }
            });

        }
        else
        {
            res.send("Passwords do not match. please <a href='/register'>try again</a> " );
        }   

});

    server.listen(3000);

这是我的客户:

<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- <script type='text/javascripts', src='/javascripts/client.js'></script> -->
<link rel='stylesheet', href='/stylesheets/style.css'>
<script>

jQuery(document).ready(function () {
    var log_chat_message = function  (message, type, divId) {
        var li = jQuery('<li />').text(message);

        if (type === 'system') {
            li.css({'font-weight': 'bold','color': '#F00','cursor':'pointer'});
        } else if (type === 'leave' || type === 'error') {
            li.css({'font-weight': 'bold', 'color': '#F00'});
        }

        jQuery('#'+divId).append(li);
    };


    // connect to the socket server
    var socket = io.connect("http://localhost", 3000); 


    socket.on('welcome',function(data){
        alert("yooooo");
        var username = data.username.substr(0,data.username.indexOf('@'));
        var message = "Welcome " + username  ;
        log_chat_message(message, 'system','messages');
        socket.emit('add-user',{username: username});
    });

    socket.on('entrance', function(data){
            //var message = data.username.substr(0,data.username.indexOf('@')) + " joined the chat";
            log_chat_message(data, 'system','messages');

    });

    socket.on('add-user', function(data){

        jQuery.each(data, function(key, value){
            console.log(value.username);
            log_chat_message(value.username, 'system','users-list');
        })

    });





    jQuery('#message_input').keypress(function (event) {
        if (event.which == 13) {
            socket.emit('chat', {message: jQuery('#message_input').val()});
            jQuery('#message_input').val('');
        }
    });
    jQuery('#users-list li').on('click','li',function(){
        alert('hi');
    });
    jQuery('#users-list li').click(function () {
        var index = $(this).index();
        var text = $(this).text();
        alert('Index is: ' + index + ' and text is ' + text);
        jQuery('#user').val('');
        socket.emit('request', {username: jQuery('#user').val()});

    });
});

</script>
<style type = 'text/stylesheet'>
#users-list li {
    cursor:pointer;
}
</style>
</head>

<body>
    <a href='/logout'>Log Out</a>
    <div id="wrapper" style="width:80%;margin:0 auto;">

        <!-- <input type="text" name="user" id="user"/>
        <button id="submit" value="submit">Submit</button> -->
        <div id='mainContaner' style="width:600px;height:400px;margin:0 auto;">
            <div id="online-users" style="width:150px;float:left;height:400px;padding:20px;border:1px black solid;">
                <ul id="users-list" style="list-style:none"></ul>
            </div>
            <div id= "container" style="width:350px;float:left;height:400px;padding:20px;overflow-y:scroll;border:1px black solid;">
                <ul id='messages' style="list-style:none"></ul>
            </div>
            <input type="text" name="message_input" id='message_input' style="width:390px;height:30px;margin-left:193px;margin-top:5px;"/>
        </div>

    </div>
</body>

1 个答案:

答案 0 :(得分:1)

我有同样的错误。我拿了this示例并且有效。尝试从中构建您的其余代码,然后您将找出问题所在。