简体   繁体   中英

Socket.io broadcast to room not working in socket.io v.0.9.13

socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username+' has joined this room');

is not hitting the client side. I can only see message from:

socket.emit('updateActivity', 'SERVER', 'you have CONNECTED to '+ socketEntity.roomName);

Did I do something wrong with socket.join() ?

I also tried to give the broadcast event a different name instead of updateActivity , but it won't work either.

There is no mention in the log output about the broadcast emit at all.

Question Update:

I found a solution that if I replace broadcast.to() to the following snippet, it would work:

socket.get(socketEntity.roomId, function (error, room) {
   io.sockets.in(room).emit('updateActivity', 'SERVER', 'you -joined- this group '+ socketEntity.roomName);
});

But I don't know why that is the case at the moment...so somehow the room parameter for io.sockets.in() above isn't the same as the string socketEntity.roomId ?

Original Code:

Server:

io.sockets.on ('connection', function (socket){
    socket.on('joinRoom', function(socketEntity){
        socket.join(socketEntity.roomId);
        socket.emit('updateActivity', 'SERVER', 'you have CONNECTED to '+ socketEntity.roomName);
        socket.broadcast.to(socketEntity.roomId).emit('updateActivity', 'SERVER', 'you -joined- this room'+ socketEntity.roomName);
    });
});

Client:

HTML:
 <ul id="activityList" class="dropdown-menu"></ul> 
JavaScript:
 $(document).ready(function(){ var socketEntity = {roomId:sampleRmId, roomName: "sample room"} socket.emit('joinRoom', socketEntity); socket.on('updateActivity', function (username, data){ $('#activityList').prepend('<li><a href="#"><div>'+ data +'</div></a></li>'); }); }) 

socket.broadcast will send the message to all the other clients except the client it is being called on.

socket.emit sends to that particular client only

io.sockets.emit sends to all clients

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM