【发布时间】:2017-05-16 13:40:08
【问题描述】:
我在 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事件,所以无法注销'I hear it !'这一行。
我也提到了Sending message to specific client in Socket IO,但它不起作用。
【问题讨论】:
-
你为什么使用
socket.broadcast.to(我没有在任何地方记录)而不是socket.send? -
@rpadovani 我在这里得到它socket.io/docs/server-api 以及我附加的帖子。他们官方文档中的示例:
client.broadcast.to(id).emit('my message', msg);
标签: javascript angular express socket.io