套接字IO室和名单

时间:2016-04-20 23:03:35

标签: javascript angularjs node.js socket.io

我正在尝试显示用户列表并计算MEAN堆栈应用程序中聊天室内的用户数。不幸的是,我遇到了一个非常严重的问题。每次新用户进入聊天室时,用户数都会重置。我希望即使新用户进入房间,聊天室中的当前成员仍然存在。

这是服务器端代码:

io.on('connection', function(socket){


  var users = [];
  var username = '';
  var room = '';
  console.log('a user has connected');


  socket.on('join-room', function(data){
    socket.join(data.room);
    room = data.room;
  });


  socket.on('request-users', function(){
    socket.to(room).emit('users', {users: users});
    console.log(users);
  });

  socket.on('add-user', function(data){

      io.to(room).emit('add-user', {
        username: data.username
      });
      username = data.username;
      users.push(data.username);
  });


  socket.on('disconnect', function(data){
    console.log(username + ' has disconnected');
    users.splice(users.indexOf(username), 1);
    io.to(room).emit('remove-user', {username: username});
  });
});

这是使用btford-socket.io的角度控制器:

angular.module('chatApp').controller('chatController', ['$scope', 'Socket','$cookies', '$rootScope', '$stateParams', function($scope, Socket, $cookies, $rootScope, $stateParams){
  Socket.connect();

  $scope.room = $stateParams.room;



  Socket.emit('join-room', {room:$stateParams.room}); 
  console.log($stateParams.room);

  $scope.users = [];


  if($cookies.get('token') && $cookies.get('currentUser')){
    console.log($cookies.get('currentUser'));
    Socket.emit('add-user', {username: $rootScope.currentUser});
  } else {
    bootbox.alert('You need to sign in to chat');
  }



  Socket.emit('request-users', {});


  Socket.on('users', function(data){
    $scope.users = data.users;
  });


  Socket.on('add-user', function(data) {
    $scope.users.push(data.username);
    $scope.messages.push({username: data.username, message: 'has arrived'});
  });

  Socket.on('remove-user', function(data){
    $scope.users.splice($scope.users.indexOf(data.username),1);
    $scope.messages.push({username: data.username, message: 'has left the building'});
  });


  $scope.$on('$locationChangeStart', function(event){
    Socket.disconnect(true);
  })
}]);

最后是HTML:

<div class="col-md-2" id="user-list">
  <p>Number of connected users: {{users.length}}</p>
  <ul>
    <li ng-repeat="user in users track by $index">{{user}}</li>
  </ul>
  <div class="fixed"></div>
</div>

1 个答案:

答案 0 :(得分:2)

所以我很确定这就是正在发生的事情。每个用户都有自己的套接字连接,但是当新用户连接时,它会向每个人广播此消息。这意味着它将为每个人重置变量。在连接函数之外的应用程序中声明所需的变量。