1

I am new in nodejs so may be it's question sounds weird but thing what i need is that i want to create a chat application where user logged in then they can chat each other one to one or one to many but problem is that if user refresh the browser then how can i maintain socket id of user list which i maintain in server side here is my code which i used

Server Side

var app = require('express')();
var fs = require('fs');
var forceSsl = require('express-force-ssl');

app.use(forceSsl);
var options = {
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.crt')
};
var server = require('https').createServer(options, app).listen(3000,function(){
        console.log("Https server started on port 3000");
});
var io = require('socket.io').listen(server);


var sockets = {}; 
var users = {};
io.on('connection', function(socket)
{
    console.log("Hi i am connected"); 
    // Emit the connected users when a new socket connects 
    for (var i in sockets) 
    { 
        socket.emit('user.add', { username: sockets[i].username, id: sockets[i].id  });    
    }    
    // Add a new user 
    socket.on('username.create', function (data) 
    { 
        socket.username    = data; 
        sockets[socket.id] = socket; 
        users[data]        = socket.id;
        io.emit('user.add',{ username: socket.username, id: socket.id }); 
    });    
    // Send the hug event to only the socket specified 
    socket.on('pm', function (data) 
    { 
         io.to(users[data.username]).emit('message', data.message);    
    }); 
    // Remove disconnected users 
    socket.on('disconnect', function () 
    { 
        delete sockets[socket.id]; io.emit('user.remove', socket.id);    
    }); 
});

Client Side

socket.emit('username.create', results.email);

socket.on("message", function(data) {
            //here i want to display message who send to this user
        });



        $(document).on('click','#gotou',function() 
        {
            var sendto  = $("#msgto").val();
            socket.emit("pm", {"username":sendto,"message":"Testing from "+checkusername}); 
        });   
vikas vyas
  • 76
  • 1
  • 9

2 Answers2

2

you can maintain the socket id in an array. you need to call first checkedIn event with userId to save socket id with userid. here is the example

var socketids=[];
io.on('connection', function(socket)
{
socket.on('checkedIn', function (data) 
socketids[socket.id]=data.userId
})

})
Osama Bari
  • 597
  • 3
  • 15
0

After some research I found that, there are many npm package which you can use to store session Id of Socket.IO:

  1. socket.io-sessions
  2. cookie-session

Cookie-parser and express-session come inside express package before express 4.0

Check this out, middle ware npm package it may help you to resolve your issue.

Middleware between express-session and socket.io

Works with express > 4.0.0 and socket.io > 1.0.0 and won't be backward compatible.

Example:

var app = require('express')(),
  server  = require("http").createServer(app),
  io = require("socket.io")(server),
  session = require("express-session")({
    secret: "my-secret",
    resave: true,
    saveUninitialized: true
  }),
  sharedsession = require("express-socket.io-session");


// Attach session
app.use(session);

// Share session with io sockets

io.use(sharedsession(session));

io.on("connection", function(socket) {
    // Accept a login event with user's data
    socket.on("login", function(userdata) {
        socket.handshake.session.userdata = userdata;
        socket.handshake.session.save();
    });
    socket.on("logout", function(userdata) {
        if (socket.handshake.session.userdata) {
            delete socket.handshake.session.userdata;
            socket.handshake.session.save();
        }
    });        
});

server.listen(3000);

Note - I didn't test it.This all package is implemented on Server-side.

or if you don't want to use this npm package then:

You can retrieve your socket id into variable and set it into angular-local-storage. So angular-local-storage store it after refreshing the page as well.

Example -

localStorageService.set('id', socketid);
Utkarsh Dubey
  • 703
  • 11
  • 31