Socket.io socket.broadcast.to not working

2019-05-20 04:30发布

问题:

I have in my Express server

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

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

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

回答1:

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.

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

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

to this:

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


回答2:

Do you have users join a namespace on connection?

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

You can try:

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