我在 Angular 2 上使用 Socket.Io 1.7.3 ,它连接到 ExpressJS 服务器。我无法将包发送到特定的套接字 ID,即使它们实际上匹配。
服务器实现:
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
});
});
关于Angular 2 实现:
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
客户端没有收到 sendNotificationsToUser
事件,因此无法注销行'我听到了!'
。
我还提到了Sending message to specific client in Socket IO ,但它不起作用。
最佳答案
您没有收到该消息,因为您是发件人。
socket.broadcast.emit(msg); // Every socket receives the message, but the socket
添加 toId
不会改变发件人忽略消息的事实。
如果您只想发送到套接字,只需使用socket.emit
关于javascript - Socket.io 发送到特定的 socketId 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44003166/