gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:47:13 24 4
gpt4 key购买 nike

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

  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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com