简体   繁体   中英

Socket.io, emit to a single client

I have a chat app that allows multiple people to connect to a chatroom, When a new client connects to the chatroom i want to be able to show them the chat history, i've done his my emitting an chat history but obviously that updates everyone in the chat leading to duplicate messages.

How would i single out the new user and display the chat just to them?

this is the server code

socket.on('chat history', function(){
   console.log("Chat History");

   posts.find({chatId: chatId}).then(function(chatHistory){
     console.log("Chat history", chatHistory);
     socket.emit('chat history', chatHistory);
   })


});

This is the client side code

socket.on('chat history', function(chatHistory){
   for (var key in chatHistory) {
     var obj = chatHistory[key];
     addChatMessage(obj);
   }
});

I am using the socketio example, the data is sending back to this method and the add chat message updates everyone.

In order to communicate to an individual, you'll require to capture their ID. You can do this by accessing the socket object, assuming that's the name of what you're creating on the connect action as illustrated in this block of server-side code:


io.on('connection', socket => {

  socket.on('chat history', async function(){
   console.log("Chat History");

   const chatHistory = await posts.find({chatId: chatId})

   console.log("Chat history", chatHistory)
   socket.to(socket.id).emit('chat history', chatHistory)
  })
})

In your example I've swapped the promise for async/await for the sake of readability, but you can accomplish the same using your preferred pattern. Just trust in this case that the ID which you seek to capture will always be kept to that context within the socket object that you generate on connection.

您可以使用以下代码行向特定用户/客户端发送事件/消息:

socket.broadcast.to(socketid).emit('chatHistory', data);

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