简体   繁体   中英

Socket.io - send different data to sender and clients?

I am learning NodeJS and Socket.IO and have been following the various tutorials dotted about, mainly focusing on making a basic chatroom.

My app works so far: being able to send messages with clients being able to move to different "rooms".

Now I am trying to tidy it up and make it look the part.

I am stumbling with the follow idea:

When user A moves form room A to B, an emit() method is sent to update an array with a user count, which in turn is sent back to the sender. A list of rooms in a side panel is then updated eg Room A (0), Room B (1).

Now, emitting the new data to the sender is easy and works, the room list gets updated, and the other rooms (that the sender is not in) have hyperlinks (this is how the user moves between rooms)

But I want to send data to the other clients, so their room lists also get updated. Sending the same data as before means the other clients's rooms list is incorrect, as the data is referencing the new room name the sender joined, not the room the other client is currently in.

Some code:

socket.on('switchRoom', function(data) {
    var newroom = sanitize(data).escape().trim();

    socket.leave(socket.room);

    socket.join(newroom);

    socket.room = newroom;

    socket.emit('updaterooms', rooms, newroom);

    // this is the problem area, socket.room should be the socket.room data for the non-sending client
    //socket.broadcast.emit('updaterooms', rooms, socket.room);
});

How would I emit to all other clients (not the sender) with the data contained in their own socket "session" (ie socket.room)?

You will need to emit a generated message that's catered to each socket. What you will need to do is iterate through each socket, emitting the custom message based on each socket, for example:

io.sockets.on('connect', function(socket) {
    socket.on('switchRoom', function(data) {
        var newroom = sanitize(data).escape().trim();

        socket.leave(socket.room);

        socket.join(newroom);

        socket.room = newroom;

        socket.emit('updaterooms', rooms, newroom);

        io.sockets.clients.forEach(function(client) {
            if (socket != client) {
                client.emit('updaterooms', rooms, client.room);
            }
        });
    });
});

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