node.js socket.io 私信
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11356001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
socket.io private message
提问by Trevor Newhook
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?
我一直在网上搜索,但没有运气。我想弄清楚如何从一个用户向另一个用户发送私人消息。有很多片段,但我不确定客户端/服务器交互。如果我有要发送到的套接字的 ID,我如何将它发送到服务器,以及如何确保服务器只将消息发送到那个接收者套接字?
Is there a tutorial or walkthrough that anyone knows of?
是否有任何人都知道的教程或演练?
回答by Brad
No tutorial needed. The Socket.IO FAQis pretty straightforward on this one:
不需要教程。该Socket.IO常见问题是在这一个非常简单的:
socket.emit('news', { hello: 'world' });
EDIT:Folks are linking to this question when asking about how to get that socketobject 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:
编辑:人们在询问socket以后如何获取该对象时会链接到这个问题。没有必要。当新客户端连接时,在您保留用户信息的任何对象上保存对该套接字的引用。我的评论来自以下:
In the top of your script somewhere, setup an object to hold your users' information.
var connectedUsers = {};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');
在脚本顶部的某个地方,设置一个对象来保存用户的信息。
var connectedUsers = {};在您的
.on('connection')函数中,将该套接字添加到您的新对象中。connectedUsers[USER_NAME_HERE] = socket;然后您可以在以后轻松检索它。connectedUsers[USER_NAME_HERE].emit('something', 'something');
回答by almypal
Here's a code snippet that should help:
这是一个应该有帮助的代码片段:
Client-side (sending message)
客户端(发送消息)
socket.emit("private", { msg: chatMsg.val(), to: selected.text() });
where torefers to the id to send a private message to and msgis the content.
其中to是指要向其发送私人消息的 id,msg是内容。
Client-side (receiving message)
客户端(接收消息)
socket.on("private", function(data) {
chatLog.append('<li class="private"><em><strong>'+ data.from +' -> '+ data.to +'</strong>: '+ data.msg +'</em></li>');
});
where chatLogis a div displaying the chat messages.
chatLog显示聊天消息的 div在哪里。
Server-side
服务器端
client.on("private", function(data) {
io.sockets.sockets[data.to].emit("private", { from: client.id, to: data.to, msg: data.msg });
client.emit("private", { from: client.id, to: data.to, msg: data.msg });
});
回答by Peter Moses
Although we have nice answers here. However, I couldn't grasp the whole client server unique user identification pretty fast, so I'm posting this simple steps in order to help whoever is struggling as i did.....
虽然我们在这里有很好的答案。但是,我无法很快掌握整个客户端服务器的唯一用户标识,所以我发布了这个简单的步骤,以帮助像我一样苦苦挣扎的人......
At the client side, Get the user's ID, in my case I'm getting the username...
在客户端,获取用户 ID,在我的情况下,我获取用户名...
Client side user registration
客户端用户注册
//Connect socket.io
var systemUrl = 'http://localhost:4000';
var socket = io.connect(systemUrl);
//Collect User identity from the client side
var username = prompt('Enter your Username');
socket.emit('register',username);
The Listen to register on the server side to register user's socket to connected socket
服务端的Listen to register 将用户的socket注册到连接的socket
Serve side code User registration
服务端代码用户注册
/*Craete an empty object to collect connected users*/
var connectedUsers = {};
io.on('connection',function(socket){
/*Register connected user*/
socket.on('register',function(username){
socket.username = username;
connectedUsers[username] = socket;
});
});
Send Message from the client side
从客户端发送消息
$(document).on('click','.username',function(){
var username = $(this).text(),
message = prompt("type your message");
socket.emit('private_chat',{
to : username,
message : message
});
});
Receive message on server and emit it to private user
在服务器上接收消息并将其发送给私人用户
/*Private chat*/
socket.on('private_chat',function(data){
const to = data.to,
message = data.message;
if(connectedUsers.hasOwnProperty(to)){
connectedUsers[to].emit('private_chat',{
//The sender's username
username : socket.username,
//Message sent to receiver
message : message
});
}
});
Receive message on client and display it
在客户端接收消息并显示它
/*Received private messages*/
socket.on('private_chat',function(data){
var username = data.username;
var message = data.message;
alert(username+': '+message);
});
This is not the best, however you can start from here....
这不是最好的,但是你可以从这里开始......
回答by Matthew Clark
The easiest way I can think of is to have an hash of all the users on using their id or name as the key and have their socket as part of the value then when you want to send a message to just them you pull that socket and emit on it... something like this:
我能想到的最简单的方法是让所有用户使用他们的 id 或名称作为键的哈希,并将他们的套接字作为值的一部分,然后当你想向他们发送消息时,你拉那个套接字,然后发射它......像这样:
users[toUser].emit('msg',"Hello, "+toUser+"!");
回答by Ali_Hr
if you have a web site that has register users with uid then you can create a room for each user and name the room by uid of the user.
如果您有一个使用 uid 注册用户的网站,那么您可以为每个用户创建一个房间,并通过用户的 uid 命名房间。
first connect client to the server using :
首先使用以下方法将客户端连接到服务器:
var socket = io('server_url');
on the server side create an event for detecting client connection:
在服务器端创建一个事件来检测客户端连接:
io.on('connection', function (socket) {}
then you can emit to client inside it using socket.emit();and ask uid of current user.
然后您可以使用socket.emit();并询问当前用户的 uid向其中的客户端发送。
on the client side create an event for this request and then send uid of the user to server.
在客户端为此请求创建一个事件,然后将用户的 uid 发送到服务器。
now on server side join the connected socket to room using :
现在在服务器端使用以下方法将连接的套接字连接到房间:
socket.join(uid);
console.log('user ' + socket.user + ' connected \n');
now you can send private message to a user using following line:
现在您可以使用以下行向用户发送私人消息:
io.to(uid).emit();
if you use the code above, it doesn't matter how many tab user has already open from your web site . each tab will connect to the same room.
如果您使用上面的代码,则用户已经从您的网站打开了多少选项卡并不重要。每个选项卡将连接到同一个房间。
回答by user3506100
in socket.io 1.0 use
在 socket.io 1.0 中使用
io.sockets.connected[<socketid>]
you can store just socket id. like so:
您可以只存储套接字 ID。像这样:
var users = {};
users[USER_NAME] = socket.id;
then:
然后:
io.sockets.connected[users[USER_NAME]]
.emit('private', {
msg:'private message for user with name '+ USER_NAME
});
回答by J. Jerez
You can create an unique room for messaging between USER_A and USER_B and both users must join to this room. You may use an UUID as a ROOM_ID (the 'socketId' in the following example).
您可以为 USER_A 和 USER_B 之间的消息创建一个独特的房间,并且两个用户都必须加入这个房间。您可以使用 UUID 作为 ROOM_ID(以下示例中的“socketId”)。
io.on('connection', socket => {
socket.on('message', message => {
socket.to(message.socketId).emit('message', message);
});
socket.on('join', socketId => {
socket.join(socketId);
});
});
See Joining Roomsand Emit Cheatsheet

