socket与节点断开连接

时间:2014-04-11 13:54:56

标签: node.js express socket.io node.js-connect

如何找到与会话相关联的套接字?我在"授权"我的node.js服务器端js上的事件。现在我想在我的" logout"中断开套接字。请求,但它对我不起作用。这是我的代码。

var express = require('express'),
    redis = require('redis'),
    RedisStore = require('connect-redis')(express),
    store = new RedisStore({ host: '127.0.0.1', port: 6379 }),
    parseCookie = express.cookieParser(secretkey);

var app = express();
var server = require("http").createServer(app),
    io = require("socket.io").listen(server, { log: false }),

app.use(express.cookieParser());
app.use(express.session({ secret: secretkey, key: 'express.sid', store: store, cookie: { maxAge: 3600000 } })); 
app.use(express.methodOverride());

io.set('authorization', function (handshakeData, callback) {
    if (handshakeData.headers.cookie) {
        parseCookie(handshakeData, null, function(err) {
            handshakeData.sessionID = handshakeData.signedCookies['express.sid'];
            //or if you don't have signed cookies
            //handshakeData.sessionID = handshakeData.cookies['express.sid'];

            console.log('manish in parseCookie 2 ' + handshakeData.sessionID + ', ' + ioClient);
            store.get(handshakeData.sessionID, function (err, session) {
                console.log('getting result ' + err + ', ' + session);
                if (err || !session) {
                    // if we cannot grab a session, turn down the connection
                    callback('Session not found.', false);
                } else {
                    //console.log('getting connection ' + session);
                    // save the session data and accept the connection
                    handshakeData.session = session;
                    callback(null, true);
                }
            });
        });
    } else {
        return callback('No cookie transmitted.', false);
    } 
    //callback(null, true);
});

io.sockets.on('connection', function(socket) {
    console.log('A socket with sessionID ' + socket.handshake.sessionID + ' connected!');
    socket.on('disconnect', function() {
        console.log('socket.on.disconnect ' + socket.handshake.sessionID); 
    });
    socket.on('error', function(err) {
        if(err === 'handshake error') {
            console.log('handshake error', err);
        } else {
            console.log('io error', err);
        }
    });     

    socket.on('message', function(data) { 
        console.log('messege received on server is "' + data + '"');
    });

});

现在当用户单击注销时,我想从此方法断开套接字;

app.post('/logout', function (req, res) {
    try {
        //here is my database logic
       //And here I want to disconnect socket, 
       io.sockets.socket(req.session.id).disconnect();
    }
    catch (err) { nodeUtil.errorLog2(res, 'trycatch', 6, err, 'app.js', 'logout'); }
});

这不会触发任何错误,也不会进入socket.on(" disconnected")事件。那么我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

嗯..试试这个

io.sockets.socket(socket.id).emit('disconnect')