简体   繁体   中英

Socket.io: How to uniquely identify a connection on client and server?

My app supports multiple socket.io clients from the same host (IP address). For diagnostics, I need to be able correlate client and server logs to identify which client the server is talking to. Does socket.io provide a way to uniquely identify a connection?

You can use session+cookies: Here's a library that you can use or learn from: session-socket.io . You'll find plenty of examples on their README page.

What I do is that within /routes/socket.js, I have these added to my requires:

var thisApp = require('../app');
var cookieSig = require('express/node_modules/cookie-signature');
var cookie = require('cookie');
var connect = require('express/node_modules/connect')
    , parseSignedCookie = connect.utils.parseSignedCookie;

This answer assumes you have a session store of some kind that you can access via thisApp.thisStore. In my case, in the main app.js, I set up a session store using kcbanner's connect-mongo (available via npm and github.com) using a MongoDB back-end hosted on MongoLab for mine. In the session store, for each session, you can have a unique username, or some other identifier that goes along with that session. Really, you can tack any data you want to that session. That's how you'd tell them apart.

The code I use looks like this:

module.exports = function (socket) {
  socket.on('taste:cookie', function (data, callback) {
    console.log("taste:cookie function running");

    //get the session ID
    var sid = data.sid;
    sid = parseSignedCookie(sid['connect.sid'], "mySecret");
    console.log("sid: ",sid);

    //get the handshake cookie
    var hssid = cookie.parse(socket.handshake.headers.cookie);
    hssid = parseSignedCookie(hssid['connect.sid'], "mySecret");
    console.log("hssid: %s",hssid);

    if(sid) {
        if(sid['connect.sid']) { 
            sid = sid['connect.sid'].slice(2);
            console.log("sliced the sid: %s",sid);
            sid = cookieSig.unsign(sid, "mySecret");
            hssid = sid;
        }

        if(hssid != sid) {
            console.log("browser cookie not set right; rectifying...");
            data.sid = hssid;
            sid = hssid;
        }
        else console.log("browser cookie was set right");
    }
    thisApp.thisStore.get(sid, function(err, gotsession) {
        if(err || !gotsession) {
            //handle error
            return;
        } else {
            if(gotsession.username) {
                callback(0, {username:gotsession.username});
            }
            else callback(1, {username:""});
        }
    });
});

Maybe there's a more elegant way to do this, but this does work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM