Javascript Socket.io发送到特定socketId不工作
我正在Angular 2上使用Socket.io1.7.3,它连接到ExpressJS服务器。我无法将包发送到特定的套接字id,因为它们实际上是匹配的 服务器实现:Javascript Socket.io发送到特定socketId不工作,javascript,angular,express,socket.io,Javascript,Angular,Express,Socket.io,我正在Angular 2上使用Socket.io1.7.3,它连接到ExpressJS服务器。我无法将包发送到特定的套接字id,因为它们实际上是匹配的 服务器实现: socket.on('subscribeNotification', function(data){ // Get new notification by user_id here .... console.log('Got notification request'); consol
socket.on('subscribeNotification', function(data){
// Get new notification by user_id here ....
console.log('Got notification request');
console.log('Your Id is: '+socket.id);
socket.broadcast.to(socket.id).emit('sendNotificationsToUser', {
text: 'hello',
id: socket.id
});
socket.emit('claimId', {
id: socket.id
});
});
subscribeNotificationEvent(userId: string) {
let socket = this.socket;
let data = {
user_id: userId
};
// Emit socket
socket.emit('subscribeNotification', data);
}
listenToNotification() {
let socket = this.socket;
socket.on('sendNotificationsToUser', function (data) {
console.log('I hear it !');
});
socket.on('claimId', (data) => {
console.log('My id is: ' + data.id);
})
}
在角度2的实施上:
socket.on('subscribeNotification', function(data){
// Get new notification by user_id here ....
console.log('Got notification request');
console.log('Your Id is: '+socket.id);
socket.broadcast.to(socket.id).emit('sendNotificationsToUser', {
text: 'hello',
id: socket.id
});
socket.emit('claimId', {
id: socket.id
});
});
subscribeNotificationEvent(userId: string) {
let socket = this.socket;
let data = {
user_id: userId
};
// Emit socket
socket.emit('subscribeNotification', data);
}
listenToNotification() {
let socket = this.socket;
socket.on('sendNotificationsToUser', function (data) {
console.log('I hear it !');
});
socket.on('claimId', (data) => {
console.log('My id is: ' + data.id);
})
}
记录结果
服务器:
Got notification request
Your Id is: bSCHMUL2bJJQCXkxAAAC
My id is: bSCHMUL2bJJQCXkxAAAC
客户端:
Got notification request
Your Id is: bSCHMUL2bJJQCXkxAAAC
My id is: bSCHMUL2bJJQCXkxAAAC
客户端未接收到sendNotificationsToUser
事件,因此无法注销行“我听到了!”代码>
我也提到过,但它不起作用 您没有收到邮件,因为您是发件人
socket.broadcast.emit(msg); // Every socket receives the message, but the socket
添加toId
不会改变发送者忽略消息的事实
如果您不想只发送到套接字,只需使用socket.emit
即可,因为您是发件人,所以您没有收到消息
socket.broadcast.emit(msg); // Every socket receives the message, but the socket
添加toId
不会改变发送者忽略消息的事实
如果您不想只发送到套接字,只需使用socket.emit
为什么要使用socket.broadcast.to
(我在任何地方都没有文档记录)而不是socket.send
?@rpadovani我从这里以及我所附的帖子中获得它。他们官方文档中的示例:client.broadcast.to(id.emit('my message',msg)
为什么使用socket.broadcast.to
(我在任何地方都没有文档记录)而不是socket.send
?@rpadovani我从这里以及我所附的帖子中获得它。他们官方文档中的示例:client.broadcast.to(id.emit('my message',msg)感觉就像我走到门口给自己发了封信。谢谢你。我感觉自己走到门口,给自己发了封信。非常感谢。