【问题标题】:Socket.io Send to specific socketId not workingSocket.io 发送到特定的 socketId 不起作用
【发布时间】: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


【解决方案1】:

您没有收到邮件,因为您是发件人。

socket.broadcast.emit(msg); // Every socket receives the message, but the socket

添加toId 不会改变发件人忽略消息的事实。

如果您只想发送到套接字,只需使用socket.emit

【讨论】:

  • 感觉就像我走到门口,给自己寄了一封信。谢谢。
猜你喜欢
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 2014-07-30
  • 1970-01-01
  • 2012-07-08
  • 2015-07-11
相关资源
最近更新 更多