node.js - 我如何仅向目标用户发送?

标签 node.js express socket.io

我的目标是向其他用户发送实时通知。

  1. 用户A浏览,发现用户B
  2. 用户 A 点击“添加好友”
  3. 用户 B 收到通知

我同时使用了iosocket来发出,发生了什么

  1. io 的情况是,它向所有连接的用户发送。
  2. 套接字的情况,是它向自身发出信号。

如果您看到下面的代码,我使用的是 socket.request.user ,我是通过使用 Passport.socketio 库得到的,只是想澄清一下。

代码

服务器端

io.on('connection', function() {
   socket.on('friendsRequest', function(data) {
      var userId = data;

      User.update(
        {
          _id: userId,
          'friendsRequested.requestee': { $ne: socket.request.user._id}
        },
        {
          $push: { friendsRequested: { requestee: socket.request.user._id } },
        }, function(err, count) {
          if (err) return next(err);
          console.log("Successful");
          socket.emit('friendsRequest', socket.request.user);
        });
      });

});

客户端

$(document).on('click', "#addFriend", function(e){
  e.preventDefault();
  var userId = $('#userId').val(); // Getting the userId from the input hidden (This is User B _id from mongoDB)
  $('#addFriend').removeClass('btn-default').addClass('btn-success') // Change the button to green color
  .html('<span class="glyphicon glyphicon-ok"></span> Added').attr('id', 'addFriend');
  socket.emit('friendsRequest', userId); // Emit the userId back to the server.
});

socket.on('friendsRequest', function(data) { // if successful

  var totalRequests = parseInt($('#totalRequests').html()); // Get the current total friendsRequest
  totalRequests += 1; // Increment by 1
  $('#totalRequests').html(totalRequests); // Change it to the current totalRequest
  $('#friendsRequested').append('<li>' + data._id + '</li>');
});

再假设用户A点击用户B页面上的添加好友按钮,为什么只有用户B收到通知而用户A却收不到通知?

最佳答案

以下代码显示了一个仅基于套接字的简约但可运行的示例:

var net = require('net');
var users = [];    // sockets are stored here

var server = net.createServer(function(socket) {
    users.push(socket);                      // store socket to var users
    socket.write('you are connected\n');     // message to current socket
    for (var i=0; i<users.length; i++) {
        if (users[i] == socket) {
            continue;                        // skip current socket
        }
        users[i].write('new user joined\n'); // send to all other sockets
    }
}).listen(3000);

您必须存储每个套接字才能单独使用每个套接字。

上面的示例展示了如何避免使用某一特定套接字,但如果您只想使用某一特定套接字,则过程类似。

正如 malix 所指出的,您需要添加一个信息以便稍后能够识别该特定套接字,例如电子邮件地址或用户 ID。

关于node.js - 我如何仅向目标用户发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35022367/

相关文章:

javascript - 在 Ubuntu 16 服务器上运行使用 Firebird 的 nodejs 应用程序

javascript - Azure 应用服务中的 process.env.NODE_ENV 在哪里

javascript - 使用 Node.js 初始化和配置 AWS

node.js - 不同集合中文档之间的MongoDB关系

express - Multer 没有通过快速放置路线

Java Socket IO 不发送到 Node.js,但可以连接和接收

node.js - "The installer has encountered an unexpected error installing this package..."。是否可以在 Windows XP 上安装 Node.js (v0.10.15)?

node.js - 如何为 API 提供 SSL?

node.js - socketio-jwt 断开过期的 token

node.js - Socket.io 如何检查用户是否正在输入并将其广播给其他用户