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

前端 未结 2 1710
梦如初夏
梦如初夏 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: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);
    

提交回复
热议问题