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

标签 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 实现:

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/

相关文章:

Javascript DOM : Pinpointing "input" elements by their type?

javascript - 如何从所有匹配的元素中获取数据?

javascript - 未定义不是对象 - Angular $rootScope.user.userMessage

node.js - 在 express 中添加故意延迟

javascript - jQuery 按值选择单选?

javascript - Angular 如何使用 querylist 对象?

css - PrimeNG 确认对话框 (OverLay) 没有内置样式 (css)

html - 检查电子邮件是否匹配模糊

javascript - 如何在 Node js Controller 文件中引用 Elastic Search JavaScript 客户端库

node.js - 在expressjs服务器和vuejs客户端之间使用快速 session