Node.js 如何仅向目标用户发射?
我的目标是向另一个用户发送实时通知Node.js 如何仅向目标用户发射?,node.js,express,socket.io,Node.js,Express,Socket.io,我的目标是向另一个用户发送实时通知 用户A浏览,找到用户B 用户A单击“添加朋友” 用户B收到了通知 我使用了io和socket来发射,发生了什么 io情况下,它向所有连接的用户发射 插座的情况下,是它自己发射 如果您看到下面的代码,我使用的是socket.request.user,我是通过使用passport.socketio库得到的,只是想澄清一下 代码 服务器端 io.on('connection', function() { socket.on('friendsRequest',
io
和socket
来发射,发生了什么
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>');
});
$(文档)。在('click')、“#addFriend”上,函数(e){
e、 预防默认值();
var userId=$('#userId').val();//从隐藏的输入中获取用户id(这是来自mongoDB的用户B_id)
$('#addFriend').removeClass('btn-default').addClass('btn-success')//将按钮更改为绿色
.html('Added').attr('id','addFriend');
emit('friendsRequest',userId);//将userId发送回服务器。
});
on('friendsRequest',函数(数据){//如果成功
var totalRequests=parseInt($('#totalRequests').html();//获取当前的好友总数请求
totalRequests+=1;//递增1
$('#totalRequests').html(totalRequests);//将其更改为当前的totalRequest
$(“#friendsRequested”)。追加(“”+数据。_id+” );
});
同样,假设用户A单击用户B页面上的“添加朋友”按钮,那么如何仅用户B获得通知而用户A不获得通知?我们在Express上使用,并通过电子邮件存储套接字:
var app = feathers(); // same as app = express();
app.sockets = {};
//...
io.on('connection', function(socket) {
// feathers puts the current user on the socket object for you, but you can roll your own
// in that case, replace email with some other unique user data
var email = socket.feathers.user.email;
if (email) {
app.sockets[email] = socket;
}
请注意,socket
来自('connection')io.on的参数[0]
然后你可以针对任何电子邮件
//find the user's socket and emit to it...
var target = app.sockets[toEmail];
target && target.emit('friendsRequest', {
message: 'whatever',
broadcast: false
});
顺便说一句,你不需要用羽毛来做这个。。。如果不需要,只需将一些唯一的用户数据与“连接”上的套接字关联,并在只想向该用户发送内容时查找套接字…以下代码显示了一个仅基于套接字的简单但可运行的示例:
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);
var net=require('net');
var users=[];//插座存储在这里
var server=net.createServer(函数(套接字){
users.push(socket);//将套接字存储到var用户
socket.write('您已连接\n');//消息到当前套接字
对于(var i=0;i每个套接字都由一个id标识,如果知道它,您只能向该套接字发出如下信息:
io.sockets.connected[id].emit('friendsRequest', data);
因此,您可以将userId设置为从客户端发送它的每个套接字的属性,例如(服务器端):
或者使用passport.socketio,您可以:
socket.on('setuserid, function(){
socket.userid=socket.request.user._id;
})
当发送好友请求时,循环连接的套接字(服务器端):
什么是app.sockets?你能解释一下它实际上是什么吗?对不起,app来自express(),app.sockets只是一个普通的对象app.sockets={};
因为我的问题更多的是关于,我如何向我以外的其他用户发送实时通知。您需要将套接字和一些东西存储在一起,以便以后使用。然后您可以引用该套接字。例如,如果您只想向第一个连接的用户发送消息,则使用用户[0]。编写('hello first user\n'))
如果使用数据库或数组是好的,使用for循环还是不使用for循环…完全取决于您的应用程序和用例。我很确定有一些很好的工作生产系统也使用数组和for循环:)我试图遵循您的代码,但使用我的逻辑。我一直收到这个错误sockets[userId].emit(“friendsRequest”,socket.request.user);类型错误:无法读取未定义的属性“emit”
如果我使用socket.to(socketId)会怎么样?有什么区别?我从未见过,但如果工作没有区别
socket.on('setuserid, function(){
socket.userid=socket.request.user._id;
})
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");
for (s in io.sockets.connected) {
if (userId==io.sockets.connected[s].userid) {
io.sockets.connected[s].emit('friendsRequest', socket.request.user);
break;
};
}
});
});