如何在nodejs中维护用户的socketid?

时间:2017-09-28 05:37:32

标签: node.js socket.io

我是nodejs的新手,所以可能是它的问题听起来很奇怪,但我需要的是我想要创建一个聊天应用程序,用户登录然后他们可以互相聊天一对一或一对多,但问题是如果用户刷新浏览器,那么如何维护我在服务器端维护的用户列表的套接字ID是我使用的代码

服务器端

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);    
    }); 
});

客户端

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}); 
        });   

2 个答案:

答案 0 :(得分:2)

您可以在数组中维护套接字ID。您需要使用userId调用第一个checkedIn事件以使用userid保存套接字ID。 这是一个例子

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

})

答案 1 :(得分:0)

经过一些研究后我发现,有许多npm package可用于存储Socket.IO的会话ID:

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

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

    检查一下,中间件 npm包 它可以帮助您解决问题。

    Middleware between express-session and socket.io

      

    适用于 express> 4.0.0 socket.io> 1.0.0 ,不会落后   兼容。

    示例:

    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);
    
      

    注意 - 我没有测试它。这个所有包都是在服务器端实现的。

    或者如果您不想使用此npm package,那么:

    您可以将套接字ID检索到变量中并将其设置为angular-local-storage。所以angular-local-storage也会在刷新页面后存储它。

    示例 -

    localStorageService.set('id', socketid);