0

I'm using Socket.Io 1.7.3 on Angular 2 , which connect to ExpressJS Server. I can't send the package to the specific socket id, event they are actually match.

Server implementation:

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
        });
    });

And on 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);
        })
    }

Logging Result

Server:

Got notification request
Your Id is: bSCHMUL2bJJQCXkxAAAC

Client:

My id is: bSCHMUL2bJJQCXkxAAAC

The client doesn't receive sendNotificationsToUser event, so it cannot log out the line 'I hear it !'.

I have also refered to Sending message to specific client in Socket IO , but it doesn't work.

Community
  • 1
  • 1
ThangLeQuoc
  • 2,272
  • 2
  • 19
  • 30
  • Why do you use `socket.broadcast.to` (that I do not se documented anywhere) instead of `socket.send`? – rpadovani May 16 '17 at 13:44
  • @rpadovani I get it here https://socket.io/docs/server-api/ and also from the post I attached. The example in their official doc: `client.broadcast.to(id).emit('my message', msg);` – ThangLeQuoc May 16 '17 at 13:47

1 Answers1

3

You are not receiving the message because you are the sender.

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

Adding the toId doesn't change the fact that the sender ignore the message.

If you want ot send only to the socket, just use socket.emit

rpadovani
  • 7,101
  • 2
  • 31
  • 50