socket.io 私信 [英] socket.io private message
问题描述
我一直在网上搜索,但没有运气.我想弄清楚如何从一个用户向另一个用户发送私人消息.有很多片段,但我不确定客户端/服务器交互.如果我有要发送到的套接字的 ID,我如何将它发送到服务器,以及如何确保服务器只将消息发送到那个接收者套接字?
I've beeen scouring the Net with no luck. I'm trying to figure out how to send a private message from one user to another. There are lots of snippets, but I'm not sure about the client/server interaction. If I have the ID of the socket I want to send to, how do I send it to the server, and how do I ensure the server only sends the message to that one receiver socket?
是否有任何人都知道的教程或演练?
Is there a tutorial or walkthrough that anyone knows of?
推荐答案
无需教程.Socket.IO FAQ 在这方面非常简单:
No tutorial needed. The Socket.IO FAQ is pretty straightforward on this one:
socket.emit('news', { hello: 'world' });
人们在稍后询问如何获取该 socket
对象时会链接到这个问题.没有必要.当新客户端连接时,在您保留用户信息的任何对象上保存对该套接字的引用.我的评论来自以下:
Folks are linking to this question when asking about how to get that socket
object later. There is no need to. When a new client connects, save a reference to that socket on whatever object you're keeping your user information on. My comment from below:
在脚本顶部的某处,设置一个对象来保存用户信息.
In the top of your script somewhere, setup an object to hold your users' information.
var connectedUsers = {};
在您的 .on('connection')
函数中,将该套接字添加到您的新对象中.connectedUsers[USER_NAME_HERE] = socket;
然后你可以在以后轻松检索它.connectedUsers[USER_NAME_HERE].emit('something', 'something');
In your .on('connection')
function, add that socket to your new object. connectedUsers[USER_NAME_HERE] = socket;
Then you can easily retrieve it later. connectedUsers[USER_NAME_HERE].emit('something', 'something');
这篇关于socket.io 私信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!