套接字IO发送到指定的用户ID [英] Socket IO send to specified user ID

查看:121
本文介绍了套接字IO发送到指定的用户ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据发送给指定的用户,而不是其他任何人。

I want to send data to the specified user, and no one else.

目前要向我所做的每个人广播:

currently to broadcast to everyone I do:

socket.on('newChatMessage', function (message) {
socket.broadcast.emit('newChatMessage_response', { data: message});
});

现在我想做的就是:

socket.on('newChatMessage', function (message) {
socket.to(5).send('newChatMessage_response', { data: message});
});

到(5)将是ID为5的用户。

to(5) would be the user with the ID of 5.

推荐答案

我认为缺少的部分是在这个函数中: io.sockets.on('connection',function(socket) {...}); - 每次有连接事件时都会执行该函数。每次该事件触发时,'socket'参数引用一个全新的套接字对象,代表新连接的用户。然后,您需要以稍后可以查找的方式将该套接字对象存储在某处,以便在其上调用send或emit方法,如果您需要发送仅由该套接字看到的消息。

I think the missing piece for you is inside this function: io.sockets.on('connection', function(socket) { ... });- That function executes every time there is a connection event. And every time that event fires, the 'socket' argument references a brand new socket object, representing the newly connected user. You then need to store that socket object somewhere in a way that you can look it up later, to call either the send or emit method on it, if you need to send messages that will be seen by only that socket.

这是一个快速的例子,可以帮助你入门。 (注意:我没有测试过这个,我也不建议这是你做的事情的最佳方式。我只是在答案编辑器中写下来给你一个想法如何可以做你想要做的事情)

Here's a quick example that should get you started. (Note: I haven't tested this, nor do I recommend that it's the best way to do what you're trying to do. I just wrote it up in the answer editor to give you an idea of how you could do what you're looking to do)

var allSockets = [];
io.sockets.on('connection', function(socket) {
  var userId = allSockets.push(socket);
  socket.on('newChatMessage', function(message) {
    socket.broadcast.emit('newChatMessage_response', {data: message});
  });
  socket.on('privateChatMessage', function(message, toId) {
    allSockets[toId-1].emit('newPrivateMessage_response', {data: message});
  });
  socket.broadcast.emit('newUserArrival', 'New user arrived with id of: ' + userId);
});

编辑:如果是id,则指的是socket.io指定的id值,而不是您已分配的值,您可以使用 var socket = io.sockets.sockets ['1981672396123987']; 获取具有特定id值的套接字(以上语法测试使用socket.io v0.7.9)

If by id you're referring to the id value that socket.io assigns, not a value that you've assigned, you can get a socket with a specific id value using var socket = io.sockets.sockets['1981672396123987']; (above syntax tested using socket.io v0.7.9)

这篇关于套接字IO发送到指定的用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆