Socket.io发送到特定的socketId不起作用

时间:2017-05-16 13:40:09

标签: javascript angular express socket.io

我在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 Implementation

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,但它不起作用。

1 个答案:

答案 0 :(得分:2)

由于您是发件人,因此您没有收到该邮件。

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

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

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

相关问题