【问题标题】:Socket.io, emit to a single clientSocket.io,发送到单个客户端
【发布时间】:2017-10-24 12:21:54
【问题描述】:

我有一个允许多人连接到聊天室的聊天应用程序,当新客户连接到聊天室时,我希望能够向他们显示聊天历史记录,我已经完成了他的发布聊天历史记录,但显然这会更新聊天中的每个人,从而导致重复消息。

我将如何挑选出新用户并向他们显示聊天内容?

这是服务器代码

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);
   })


});

这是客户端代码

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

我正在使用 socketio 示例,数据正在发送回此方法,并且添加聊天消息会更新每个人。

【问题讨论】:

  • 服务器端,通过单个套接字 (socket.emit('chat history')) 发射,而不是房间中的所有套接字 (io.to('some room').emit('chat history'))。
  • @JeremyThille 嗨,你能告诉我这个更详细吗?
  • 好吧,没有更多细节了。你有一个人socket,然后你用它来向一个特定的人发送你的信息:socket.emit("chat history", data)。我不知道怎么说更好:) io.on( "connection", function(socket){ socket.emit("chat history", someData); })
  • @JeremyThille 嘿,当我使用 socket.emit("chat history", data) 时,它会更新聊天中的每个人。
  • 为什么要在服务器端监听聊天记录?服务器将聊天记录发送到客户端,它永远不会接收它。

标签: javascript sockets socket.io


【解决方案1】:

为了与个人交流,您需要获取他们的 ID。您可以通过访问 socket 对象来执行此操作,假设这是您在连接操作上创建的名称,如以下服务器端代码块所示:


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)
  })
})

在您的示例中,为了便于阅读,我将 promise 替换为 async/await,但您可以使用您喜欢的模式来完成相同的操作。在这种情况下,请相信您要捕获的 ID 将始终保留在您在连接时生成的 socket 对象中的该上下文中。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 可能是一个愚蠢的问题,但我如何获得 socketid?
    • socketid 可以通过“socket.id”获取。 @ragebunny
    • 但是socket 已经是一个特定的套接字/客户端...您的代码与socket.emit() 相同
    • @mn.agg 嗨,我已经尝试过了,现在它似乎没有在客户端上点击 on('chat history')。我假设我这样做是服务器端?
    猜你喜欢
    • 2018-01-30
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 2015-07-11
    • 2018-02-13
    • 2016-10-19
    • 2014-08-17
    • 2021-06-21
    相关资源
    最近更新 更多