socket.io and node.js to send message to particular client

前端 未结 2 1672
梦如初夏
梦如初夏 2020-12-14 23:01

Sending message to all client works well but I want to send message to particular username. my server.js file looks like. What it does is when http://localhost:8080

相关标签:
2条回答
  • 2020-12-14 23:10

    You have to store all client ids and according to that you have to get id of particular client and then you use following code

    var store={};//this will store all client id and username e.g. store={jay:"34jhjshdj343sasa"}
    socket.on('pmessage', function (data) {
        var receiverUserName=data.username;
        var message=data.message;
        var id = store[receiverUserName];//get ID
        // we tell the client to execute 'updatechat' with 2 parameters
        io.sockets.emit("pvt",socket.username,data+socket.username);
        io.sockets.socket(id).emit("pvt",socket.username,data+socket.username); 
    });
    

    Then this will emit on particular client

    0 讨论(0)
  • 2020-12-14 23:16

    Try this:

    socket.on('pmessage', function (data) {
        // we tell the client to execute 'updatechat' with 2 parameters
        io.sockets.emit("pvt",socket.username,data+socket.username);
        io.sockets.socket(socket.id).emit("pvt",socket.username,data+socket.username); 
    });
    

    socket.id is saved by socket.io and it contains unique id of your client. You can check that using this:

    console.log(socket.id);
    
    0 讨论(0)
提交回复
热议问题