Sending message to specific client in Socket IO

前端 未结 3 1547
我寻月下人不归
我寻月下人不归 2020-12-22 18:26

I\'m using Socket IO v1.4.5 and have tried 3 different ways below but dont have any result.

client.emit(\'test\', \'hahahaha\');
io.sockets.socket(id).emit(\         


        
相关标签:
3条回答
  • 2020-12-22 19:06

    Socket.io Version 2.0.3+

    Sending a message to a specific socket

        let namespace = null;
        let ns = _io.of(namespace || "/");
        let socket = ns.connected[socketId] // assuming you have  id of the socket
        if (socket) {
            console.log("Socket Connected, sent through socket");
            socket.emit("chatMessage", data);
        } else {
            console.log("Socket not connected, sending through push notification");
        }
    
    0 讨论(0)
  • 2020-12-22 19:18

    To send a message to a specific client you need to do it like so:

    socket.broadcast.to(socketid).emit('message', 'for your eyes only');
    

    Here is a nice little cheat sheet for sockets:

     // sending to sender-client only
     socket.emit('message', "this is a test");
    
     // sending to all clients, include sender
     io.emit('message', "this is a test");
    
     // sending to all clients except sender
     socket.broadcast.emit('message', "this is a test");
    
     // sending to all clients in 'game' room(channel) except sender
     socket.broadcast.to('game').emit('message', 'nice game');
    
     // sending to all clients in 'game' room(channel), include sender
     io.in('game').emit('message', 'cool game');
    
     // sending to sender client, only if they are in 'game' room(channel)
     socket.to('game').emit('message', 'enjoy the game');
    
     // sending to all clients in namespace 'myNamespace', include sender
     io.of('myNamespace').emit('message', 'gg');
    
     // sending to individual socketid
     socket.broadcast.to(socketid).emit('message', 'for your eyes only');
    

    Credit to https://stackoverflow.com/a/10099325


    The easiest way rather than sending directly to the socket, would be creating a room for the 2 users to use and just send messages freely in there.

    socket.join('some-unique-room-name'); // Do this for both users you want to chat with each other
    socket.broadcast.to('the-unique-room-name').emit('message', 'blah'); // Send a message to the chat room.
    

    Otherwise, you're going to need to keep track of each individual clients socket connection, and when you want to chat you'll have to look up that sockets connection and emit specifically to that one using the function I said above. Rooms are probably easier.

    0 讨论(0)
  • 2020-12-22 19:21

    Simply do this

    io.socket.in('room').emit("send message to everyone", data);
    
    0 讨论(0)
提交回复
热议问题