Socket.io socket.broadcast.to 不工作 [英] Socket.io socket.broadcast.to not working

查看:28
本文介绍了Socket.io socket.broadcast.to 不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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' 设置此事件的处理程序时,我什么也没得到.

Surprise surprise when I setup a handler for this event on my cliens side for 'get_msg' i get nothing.

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

 })


});

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

My other client side handlers are working fine.

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

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

My version of socket.io is 1.3.7 .Am I missing something here?

推荐答案

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

socket.broadcast().to() send a message to all users that match the to() arguments EXCEPT the user who's socket it is. So, socket.broadcast.to(socket.id) will never send to the actual socket user. In fact, by default, it won't send to anyone.

直接来自 socket.io 文档:

Direct from the socket.io doc:

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

To broadcast, simply add a broadcast flag to emit and send method calls. Broadcasting means sending a message to everyone else except for the socket that starts it.

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

If you want to send to only a single socket, then just use:

socket.emit(...)

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

If you want to broadcast to a socket.id-type room and you want to include the user who's room it is, then use:

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

所以,你可以改变这个:

So, you can change this:

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

这篇关于Socket.io socket.broadcast.to 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆