Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9221429
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T03:34:39+00:00 2026-06-18T03:34:39+00:00

Here I am using get of socket-io and on every page reload it is

  • 0

Here I am using get of socket-io and on every page reload it is giving me new values ( Ideally it should come from session and should be same ). Can you please point-out the reason?

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var _ = require('lodash');
var q = require('q');

server.listen(3000);

var userCounter = 0;
    app.use(express.cookieParser());
    app.use(express.cookieSession({secret: 'secret', key: 'express.sid', cookie:{ path: '/', httpOnly: true, maxAge: (1000*3600*24)} }));
    app.use(express.static('public'))
   .use(function (req, res) {
        res.end('File not available\n');
    });

function getUserName(socket) {
    var deferred = q.defer();
    socket.get('userName', function (err, Name) {
        if (err || !Name) { // PROBLEM: It always goes in to this IF
            var userName = "Userno: " + (userCounter + 1);
            userCounter++;
            socket.set('userName', userName, function () {
                deferred.resolve(userName);
            });
        } else {
            deferred.resolve(Name);
        }
    });
    return deferred.promise;
}

io.sockets.on('connection', function (socket) {
    getUserName(socket).
        then(function (userName) {
            socket.emit("welcome", userName);
            _(io.sockets.sockets).forEach(function (eSocket) {
                if (socket !== eSocket)
                    eSocket.emit("userAdded", userName);
            });
            socket.on('disconnect', function () {
                socket.get('userName', function (err, userName) {
                    io.sockets.emit('userRem', userName);
                });
            });
        });

});
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T03:34:40+00:00Added an answer on June 18, 2026 at 3:34 am

    You haven’t implemented any session authentication for your socket.io. By default every connection to your socket.io is a new connection, although it has the same cookie ( session_id in your cookie ). There is a special option for socket.io to pass every request through authentication function something like:

    var sAuthorization = function(req, cb) {
        if ( req.headers.cookie ) { 
            cb(null, true); return; // We have cookie
        } else {
            cb(null, false); return; // We don't have cookie drop the connection
        };
    
    var socket = require('socket.io').listen(app, { authorization: sAuthorization });
        
    

    Things you should do to make it work ( I will not write this as a code, becuase there are a lot of modifications needed ) :

    1. Implement giving the user a name in your initial http connection within express ( every user should be given an username for their unique session );
    2. Implement sessionStore which can be reached by express & socket.io ( see this gist for some ideas how to do it ( it uses nowjs but it’s the sessionStore code you have to look ). Actually it’s better if you place your sessionStore in some database, not in your MemoryStore.
    3. Make your socket.io authorization sub to reach this sessionStore and get the username, then place it as a parameter for this socket as usual : socket.set('name', ....

    Pretty much that’s it. It’s not as hard as it sounds, but that’s the proper way of doing this.

    Further reading :

    1. https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO
    2. https://github.com/LearnBoost/socket.io/wiki/Authorizing

    Update :

    Look at this answer it will be very helpful for you
    Securing Socket.io

    Update II :

    I’ve created a Gist file here with that code https://gist.github.com/1b17fd2a7b324cb3411a

    var express = require('express'),
        app = express(),
        http = require('http'),
        server = http.createServer(app),
        users = 0,
        MemoryStore = express.session.MemoryStore,
        sessionStore = new MemoryStore(),
        parseCookie = require('cookie').parse,
        utils = require('connect').utils,
        io = require('socket.io').listen(server);
    
    app.use( express.bodyParser() );
    app.use( express.cookieParser('secret') );
    app.use( express.session({secret: 'secret', store:sessionStore}) );
    
    app.get('/', function(req, res) {
        var user = req.session.username ? req.session.username : null;
        if ( !user ) {
            user = 'user_' + users++;
            req.session.username = user;
            req.session.save();
        }
        res.send('<!doctype html> \
            <html> \
            <head><meta charset="utf-8"></head> \
            <body> \
                <center>Welcome ' + user + '</center> \
                <script src="/socket.io/socket.io.js"></script> \
                <script> \
                    var socket = io.connect(); \
                    socket.emit("message", "Howdy"); \
                </script> \
            </body> \
            </html>');
    });
    
    io.configure(function () {
        io.set('authorization', function (request, callback) {
            var cookie = parseCookie(request.headers.cookie);
            if( !cookie && !cookie['connect.sid'] ) {
                return callback(null, false);
            } else {
                sessionStore.get(utils.parseSignedCookie(cookie['connect.sid'], 'secret'), function (err, session) {
                    if ( err ) {
                        callback(err.message, false);
                    } else {
                        if ( session && session.username ) {
                            request.user = session.username;
                            callback(null, true);
                        } else {
                            callback(null, false);
                        }
                    }
                });
            }
        });
    });
    
    io.sockets.on('connection', function (socket) {
        socket.on('message', function(msg) {
            console.log(msg + 'from '+ socket.handshake.user);
        });
    });
    
    server.listen(8000);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using jQuery to get data from server. Data is coming. Here what
I have an issue going on here. I am using PHP to get values
I'm trying to get a std::string from my database using mysql connexion Here is
I'm trying to create a new ObjectInputStream using an InputStream retrieved from a Socket.
Here in this html i need to get the image name arrow_down using jquery
I want to get the out parameter of stored procedure using Zend framework Here's
I'm trying to get all words inside a string using Boost::regex in C++. Here's
I'm using toLocalizedTime to output a date, as below <span tal:content=python:here.toLocalisedTime(date.get('start_date'))/> This outputs eg.
I follow example from here using section listview http://lalit3686.blogspot.com/2012/05/sectionadapter.html But how can I implement
I know how to send post/get request using any HTTPClient which are explained here

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.