【问题标题】:Socket.io socket.broadcast.to not workingSocket.io socket.broadcast.to 不工作
【发布时间】:2017-01-25 19:26:57
【问题描述】:

我有我的Express 服务器

userbase = {'Fitz': '84Iw3MNEIMaed0GoAAAD'}; //Exapmle user to receive message and associated socket id



//Sending message to Example user
    socket.on('send_msg',function(data_from_client){



       //Testing  for receivers socketId


     console.log(userbase[data_from_client.to_user]);//This returns the socket id for Fitz in userbase successfully i.e 84Iw3MNEIMaed0GoAAAD



      socket.broadcast.to(userbase[data_from_client.to_user]).emit('get_msg',{msg:data_server.msg});
    });

当我在客户端为'get_msg' 设置此事件的处理程序时,我一无所获。

.factory('SocketFctry',function(){
  var socket = io('http://localhost:3002')

  return socket;
})



.controller('ChatCtrl', function($scope,SocketFctry) {

 SocketFctry.on('get_msg',function(received_message){
   console.log(received_message);
   $scope.$apply();

 })


});

我的其他客户端处理程序工作正常。

 SocketFctry.on('new_user', function(users,my_id){
    console.log(users);
    $scope.online_users = users;
    $scope.$apply();
  })

我的 socket.io 版本是 1.3.7。我在这里遗漏了什么吗?

【问题讨论】:

    标签: angularjs node.js ionic-framework socket.io


    【解决方案1】:

    socket.broadcast().to() 向与to() 参数匹配的所有用户发送消息,但socket 的用户除外。所以,socket.broadcast.to(socket.id) 永远不会发送给实际的socket 用户。事实上,默认情况下,它不会发送给任何人。

    直接来自 socket.io 文档:

    要广播,只需添加一个广播标志来发出和发送方法 来电。广播意味着向所有人发送消息,除了 用于启动它的套接字。

    如果您只想发送到单个套接字,那么只需使用:

    socket.emit(...)
    

    如果你想广播到 socket.id 类型的房间,并且你想包含它所在房间的用户,那么使用:

    io.to('some room').emit('some event'):
    

    所以,你可以改变这个:

    socket.broadcast.to(userbase[data_from_client.to_user]).emit('get_msg',{msg:data_server.msg});
    

    到这里:

    io.to(userbase[data_from_client.to_user]).emit('get_msg',{msg:data_server.msg});
    

    【讨论】:

      【解决方案2】:

      您是否有用户在连接时加入命名空间?

      socket.join(userbase[data_from_client.to_user]); //'84Iw3MNEIMaed0GoAAAD'
      

      你可以试试:

      socket.in(userbase[data_from_client.to_user]).emit('get_msg', {msg:data_server.msg});
      

      【讨论】:

      • 我理解每个连接的客户端都会自动添加到带有他的套接字#id 的房间...您使用 socket.in(socket.id) 的解决方案对我有用,但我仍然很难理解 socket.broadcast.to(socket.id) 没有不工作。在接受答案之前,我真的很想了解原因。有什么想法吗?
      猜你喜欢
      • 2018-02-15
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2012-08-14
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多