0
votes

I'm trying to loop through each user's array of sockets and send a message by their socketId... but it's not receiving it on the front end for some reason.

I tried these below, but to no avail.

https://github.com/Automattic/socket.io/issues/1618

Sending message to a specific ID in Socket.IO 1.0

Socket.io: Not able send message to particular socket using socket.id

Backend:

users.forEach(function(subDoc){
  console.log('>> notifyOnline: iterating user...')
  console.log(subDoc);

  // for every socket, send out an emit.
  for (var j = 0, arr = subDoc.socketId.length; j < arr; j++ ) {
    console.log('>> notfiyOnline: sending out good thoughts to clients...');
    console.log('>> EMITTING' + subDoc.socketId[j] + 'is type ' + typeof subDoc.socketId[j] );

    // These don't seem to do anything
    io.sockets.to(subDoc.socketId[j]).emit('notification:new', packet);
    io.to(subDoc.socketId[j]).emit('notification:new', packet);

  }; // end - for each socket
}); // end - forEach user

Frontend:

  // Listens for users followed online
  socketFactory.on('notification:new', function (data) {
    console.log('>> worldCtrl: Received live notification');
    console.log(data);
    $scope.$applyAsync(function() {
      $scope.rootUser.notifications.push(data);
    });
  }); // end - socketFactory

Edit

@jfriend00: Data structure for each user in users below. I haven't put in the code to clear old socketId, so some of them are inactive. It's the result of a mongoose query:

// Mongoose Query:
model_onlineUser.find({ 'user._id' : { $in: followers }}, function (err, users) { 
  // notify users (backend code above)
}); // end - find

// Data structure: user in users
[{ _id: 553b49db2242347514c654a9,
  user: 
   { _id: '5503530ed3e910505be02cde',
     displayName: 'some dudes name',
     photo: 'some photo url' },
  __v: 28,
  followers: 
   [ '5525d19a5fb4ee095072c4ad',
     '5525587a04f79c6e4d65015d',
     '55067b0638d1c47238ebabbb' ],
  socketId: 
   [ '2K1_8WQ1JZMUjLx3AAAF',
     'xJqixhGiRb5HYxcoAAAD',
     '7fDqV_DBP3FCTIlLAAAF' ] }]

Edit 2

New: After a user login through passport.js (facebook auth), the redirect causes socket to disconnect, so the socket.id becomes invalid... the problem now is that it is not re-establishing connection ... even with forceNew : true.

1
What is users and how is it built?jfriend00

1 Answers

0
votes

Solved:

Problem 1: Failure to reconnect.

On disconnect (after Passport login authentication), socket.io didn't re-establish connection so the socketId I had in the database became obsolete. This was solved by adding this to the client io.on('connect'):

{ 'forceNew' : true }

Problem 2: Local testing environments

My testing procedures required sending messages to users on other computers. We were testing on two separate local servers, so we were trying to emit to each other's local host. When we moved our testing to a single server, sockets started working as expected.