node.js 使用 socket.io 和空消息队列向特定客户端发送消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6913801/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:25:57  来源:igfitidea点击:

Sending message to specific client with socket.io and empty message queue

node.jsexpresssocket.io

提问by krevativ

I′m going crazy with socket.io! Documentation is so bad it's simply not true.

我对 socket.io 快要疯了!文档太糟糕了,这根本不是真的。

I want to send a feedback to specific client over socket.io

我想通过 socket.io 向特定客户端发送反馈

My server side looks like this:

我的服务器端看起来像这样:

app.get('/upload', requiresLogin, function(request, response) {
    response.render('upload/index.jade');
    io.sockets.on('connection', function (socket) {
        console.log('SOCKET ID ' + socket.id);
        io.sockets.socket(socket.id).emit('new', 'hello');
    });
});

and the client side looks like this:

客户端看起来像这样:

$(document).ready(function() {
    var socket = io.connect('http://localhost:80/socket.io/socket.io.js');
    socket.on('new', function (data) { 
        console.log(socket.id);
        console.log(data); 
        //$('#state').html(data.status);
    });
});

but the client does simply nothing. I have tried nearly everything. Can someone tell me what I am doing wrong, please! :(

但是客户端什么都不做。我几乎尝试了所有方法。有人可以告诉我我做错了什么,请!:(

回答by pkyeck

to send a message to a specific client save every one that connects to the server in an Object.

将消息发送到特定客户端,将连接到服务器的每个客户端保存在一个对象中。

var socketio = require('socket.io');
var clients = {};
var io = socketio.listen(app);

io.sockets.on('connection', function (socket) {
  clients[socket.id] = socket;
});

then you can later do something like this:

那么你以后可以做这样的事情:

var socket = clients[sId];
socket.emit('show', {});

回答by Tom Rogers

A couple of ways to send feedback to a specific client over socket.io include:

通过 socket.io 向特定客户端发送反馈的几种方法包括:

  • As stated by pkyeck, save all clients to an Object, so you can send to these specific clients later in your route handlers, e.g.:

    var sessionsConnections = {};
    sio.on('connection', function (socket) {
      // do all the session stuff
      sessionsConnections[socket.handshake.sessionID] = socket;
    });
    
  • or, use socket.io's built in support for rooms - subscribe each client to a room on connection and send via this room within route handlers, e.g.:

    sio.on('connection', function (socket) {
      // do all the session stuff
      socket.join(socket.handshake.sessionID);
      // socket.io will leave the room upon disconnect
    });
    
    app.get('/', function (req, res) {
      sio.sockets.in(req.sessionID).send('Man, good to see you back!');
    });
    
  • 如 pkyeck 所述,将所有客户端保存到一个对象,以便稍后在路由处理程序中发送到这些特定客户端,例如:

    var sessionsConnections = {};
    sio.on('connection', function (socket) {
      // do all the session stuff
      sessionsConnections[socket.handshake.sessionID] = socket;
    });
    
  • 或者,使用 socket.io 对房间的内置支持 - 在连接时为每个客户端订阅一个房间,并在路由处理程序中通过这个房间发送,例如:

    sio.on('connection', function (socket) {
      // do all the session stuff
      socket.join(socket.handshake.sessionID);
      // socket.io will leave the room upon disconnect
    });
    
    app.get('/', function (req, res) {
      sio.sockets.in(req.sessionID).send('Man, good to see you back!');
    });
    

Acknowledgement:

致谢:

http://www.danielbaulig.de/socket-ioexpress/#comment-1158

http://www.danilbaulig.de/socket-ioexpress/#comment-1158

Note that both these example solutions assume that socket.io and express have been configured to use the same session store and hence refer to the same session objects. See the links above and below for more details on achieving this:

请注意,这两个示例解决方案都假定 socket.io 和 express 已配置为使用相同的会话存储,因此引用相同的会话对象。有关实现此目的的更多详细信息,请参阅上面和下面的链接:

https://github.com/LearnBoost/socket.io/wiki/Authorizing

https://github.com/LearnBoost/socket.io/wiki/Authorizing

回答by 3rdEden

2 things

2件事

1) You should really place your io.sockets.on(..)outside your app/updateroute to prevent adding multiple listeners for clients.

1)您应该真正将您io.sockets.on(..)app/update路线放在您的路线之外,以防止为客户添加多个侦听器。

2) io.sockets.socket(id); should not be used, it should have been socket.emit('new', 'hello')

2) io.sockets.socket(id); 不应该使用,它应该被使用socket.emit('new', 'hello')

回答by Ferdi265

In socket.io 1.0, this is how it would work. It may work for lower versions, but I cannot guarantee it.

在 socket.io 1.0 中,这就是它的工作方式。它可能适用于较低版本,但我不能保证。

socket.to(socket_id_here).emit('new', 'hello');

This works because socket.io automatically adds a socket to a room with the socket's id on connection.

这是有效的,因为 socket.io 会在连接时自动将套接字添加到具有套接字 ID 的房间。

Also, if you plan to upgrade to version 1.0, there are a lot of changes to the api, so you'll sometimes have to change some code to make it work in 1.0.

此外,如果您计划升级到 1.0 版,api 会有很多更改,因此有时您必须更改一些代码才能使其在 1.0 版中工作。

回答by Williz

The correct way to do this in Socket.io 1.0+ is:

在 Socket.io 1.0+ 中执行此操作的正确方法是:

io.to(users_socket_id).emit('new', 'hello');

You can also substitute a room name for 'users_socket_id' to emit to a specific socket.io room.

您还可以将房间名称替换为“users_socket_id”以发送到特定的 socket.io 房间。

回答by Shekhar

First of all, you cannot use socket.idon client side.

首先,您不能socket.id在客户端使用。

And then change the line

然后换行

var socket = io.connect('http://localhost:80/socket.io/socket.io.js');

var socket = io.connect('http://localhost:80/socket.io/socket.io.js');

to

var socket = io.connect('http://localhost:80/');

var socket = io.connect('http://localhost:80/');

回答by Mario Mixtega

Have you tried using?

你试过使用吗?

var socket = io.connect('http://localhost:80/');

回答by Adiii

i tired with the latest version of node and socket.io below i am going to post complete code

我厌倦了下面最新版本的 node 和 socket.io 我要发布完整的代码

  <ul id="messages"></ul>
<form action="">
  <input id="id1"  /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>

  var io = io.connect();
  $('form').submit(function(){
    io.emit('drumevent', $('#id1').val());
    $('#id1').val('');
    return false;
  });
  io.on('drumevent', function(msg){
  console.log(msg);



    $('#messages').append($('<li></li>').text(msg.message+'    quantity = '+msg.quantity));
  });
</script>

server side code

服务器端代码

  var usernames = {};io.on('connection', function(socket){usernames["username"] = socket.id;
socket.on('drumevent', function(msg){     
var socketId = socket.id;io.to(socketId).emit('drumevent', data);

回答by jsb

I believe io.sockets.socket has been removed and has been a problem in Socket.IO (https://github.com/socketio/socket.io/issues/1618).

我相信 io.sockets.socket 已被删除,并且一直是 Socket.IO ( https://github.com/socketio/socket.io/issues/1618) 中的一个问题。

You can use io.sockets.connected[socket.id] and store the socket.id to reference with the user via username:

您可以使用 io.sockets.connected[socket.id] 并存储 socket.id 以通过用户名与用户引用:

var usernames = {};
usernames[username] = socket.id;
// Sending the message
io.sockets.connected[usernames[username]].emit(...);

I don't see it anywhere on the documentation so I can see how this hasn't been answered. Also, if you don't have any reference via usernames, you can instead try:

我在文档的任何地方都没有看到它,所以我可以看到这个问题没有得到解答。此外,如果您没有通过用户名获得的任何参考,您可以尝试:

users[socket.id] = socket.id;

to duplicate the key and value for easy access.

复制键和值以便于访问。

There is also possibly another way by using io.clients as described below, but I haven't used that method.

如下所述,还有另一种使用 io.clients 的方法,但我没有使用过这种方法。

OTHER SOLUTION: Send message to specific client with socket.io and node.js

其他解决方案:使用 socket.io 和 node.js 向特定客户端发送消息