Sunday, 7 May 2017

Websockets & NodeJS - Changing Browser Tabs & Sessions

I've started writing a node.js websocket solution using socket.io.

The browsers connects to the node server successfully and I get see the socket.id and all config associated with console.log(socket). I also pass a userid back with the initial connection and can see this on the server side to.

Question: I'm not sure the best way to associate a user with a connection. I can see the socket.id changes every page change and when a tab is opened up. How can I track a user and send 'a message' to all required sockets. (Could be one page or could be 3 tabs etc).

I tried to have a look at 'express-socket.io-session' but I'm unsure how to code for it and this situation.

Question: I have 'io' and 'app' variables below. Is it possible to use the 2 together? app.use(io);

Essentially I want to be able to track users (I guess by session - but unsure of how to handle different socket id's for tabs etc) and know how to reply to user or one or more sockets.

thankyou

// Required Modules
var app = require('express')();
var server = require('http').createServer(app);
var socketio = require('socket.io');
var database = require('./includes/database.js');
//var sharedSession = require('express-socket.io-session');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var redisStore = require('connect-redis')(expressSession);


// Cookie & Session Config
app.use(cookieParser());
app.use(expressSession({
    store: new redisStore({ host: 'elasticache.content.dating', port: 3679 }),
    name: 'dating-websocket-session',
    secret: "asd7fha0ds6fa6sdfia6sdgfia6sdfia63wf",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true, maxAge: 604800 }
}));


// Listener
server.listen(9999, '127.0.0.1', function() {
    console.log('HTTP NodeJS Express Server Listening on: http://localhost:9999\n');
});
var io = socketio.listen(server);


// Server Success Response
app.disable('x-powered-by');
app.get('/', function(req, res) {
    var headers = {};
    headers["Access-Control-Max-Age"] = '3600';
    headers["Access-Control-Allow-Methods"] = "POST";
    headers["Access-Control-Allow-Headers"] = "Content-Type";
    res.writeHead(200, headers);
    res.end();
});


// Share session with io sockets
//io.use(sharedSession(session));


// WebSocket Initialization
var socketList = new Array();
io.on('connection', function(socket) {
    socket.emit('message', 'Server Connected...');

    // Options
    // console.log(socket); -- Show All Socket Config
    // socket.id - Socket ID

    // Connect
    socket.on('clientRequestConnection', function (userid) {
        socket.userid = userid;
        socketList.push(socket);
        console.log('Sockets('+socketList.length+'): '+socket.userid+' <> '+socket.id);


    });

});



via Adam

No comments:

Post a Comment