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

查看:154
本文介绍了Socket 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});
});

to(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 获取具有特定 id 值的套接字.sockets.sockets['1981672396123987'];(以上语法测试使用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)

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

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