获取Socket.io中已连接用户/客户端的列表

时间:2017-06-26 11:12:29

标签: node.js express socket.io

我需要从socket.io获取已连接用户或客户端的列表以进行实时聊天。

List of connected user image

我设法显示连接到我的路由/ API的客户端列表(localhost:3003 / chat)。谁将访问此路线(授权与否)将显示如图所示。我的问题是初始访问,或者如果您尝试刷新浏览器,客户端将无法看到当前连接的用户或客户端连接的历史记录。

这是我的服务器端socket.io的示例代码,

 module.exports.initializeSocketIO = (io) => {
 io.on('connection', (socket) => { 
    socket.on('connectedUser', (users) =>{
        socket.name = users;
        io.emit('connectedUser', users);
        console.log(users + ' has joined the chat.');
    });

    socket.on('disconnect', (user) => {
        io.emit('disconnect', user);
        console.log(socket.name + ' has left the chat.');
    });

    socket.on('chatMessage', (from, msg) => {
        io.emit('chatMessage', from, msg);
        console.log('Message From: ' + from + '\n -' + msg);
    });

    socket.on('showTypingUser', (user) => {
        io.emit('showTypingUser', user);
    });
});
};

这是我的客户端socket.io的示例代码

var socket = io(); 

socket.on('connectedUser', function(users){
   var name = $('#currentUser').val();
   var me = $('#user').val(name);
   socket.name = users;
   if(users != me){
      $('#connectedUser').append('<tr><td>' + '<b>' + users + '</b>' + ' has 
      joined the discussion. </td></tr>' );
   }
});


socket.on('chatMessage', function(from, msg){
   var me = $('#user').val();
   var color = (from == me) ? 'green' : '#009afd';
   var from = (from == me) ? 'Me' : from;
   var date = new Date();
   if(from == "Me"){
      $('#messages').append('<div class="speech-bubble">'  + '<b style="color:' + color + '">' + from + ':</b> ' + msg + ' <span class="pull-right" style="color:gray">' + date.toLocaleString() + '</span>' +'</div>');
  } else {
     $('#messages').append('<div class="speech-bubble-reply">' +  '<b 
 style="color:' + color + '">' + from + ':</b> ' + msg + ' <span class="pull-right" style="color:gray">' + date.toLocaleString() + '</span>' +'</div>');
  }
});


socket.on('showTypingUser', function(user){
   var name = $('#currentUser').val();
   var me = $('#user').val(name);
   if(user != me) {
      $('#notifyUser').text(user + ' is typing ...');
   } 
   setTimeout(function(){ $('#notifyUser').text(''); }, 10000);;
});


socket.on('disconnect', function(user){
   var name = $('#currentUser').val(); 
   var me = $('#user').val(name);
   if(socket.name != name){
      $('#connectedUser').append('<tr><td>' + '<b>' + socket.name  + '</b>' + ' has left the discussion. </td></tr>' );
  }
 });


$(document).ready(function(){
   var name = $('#currentUser').val();
  $('#welcomeMessage').append('<div class="welcome-chat">Welcome to Entrenami Chat</div>')
  socket.emit('connectedUser', name);
});

注意:我正在使用express用于路由和控制器,而EJS用于我的视图。我有点卡在这里,因为我不知道如何解决我的问题。

1 个答案:

答案 0 :(得分:3)

io.engine.clientsCount返回用户连接时可以将其发送到客户端的已连接用户总数:

io.on('connection', (socket) => {
   var total=io.engine.clientsCount;
   socket.emit('getCount',total)
});