Search code examples
node.jsexpresspeerjs

How to send a notification to a specific peer using Peer.js


I'm trying to send a specific notification for each peer connected to my server.

I'm trying to send the notification in the same way the peer client works, but its methods are not supported. How can I send a notification from the server to a specific peer?

var PeerServer = require('peer').PeerServer;
var server = new PeerServer({port: 9000, path: '/myapp'});
var connected = [];
server.on('connection', function (id) {
  var idx = connected.indexOf(id); // only add id if it's not in the list yet
  if (idx === -1) {connected.push(id);}
});
server.on('disconnect', function (id) {
  var idx = connected.indexOf(id); // only attempt to remove id if it's in the list
  if (idx !== -1) {connected.splice(idx, 1);}
});

var app = express();

var turn = {
  type: 1,
  selection: "NINGUNA",
  timestamp: new Date().getTime()
};

app.get('/connected-people', function (req, res) {
  var list = connected;

  for(var i = 0; i < connected.length; i++){    
    var conn = server.connect(connected[i]);
    console.log(connected[i]);
    conn.on('open', function(){
      conn.send(turn);
    });
  }

  return res.json(connected);
});

But this way, the notification doesn't get sent to the peers. Is there a way to do it?


Solution

  • I do not have enough rep for a comment but looking at what you are trying to do I would think you could just use socket.io for the direct server to peer communication.

    Looking at the docs for PeerJS shows that

    To broker connections, PeerJS connects to a PeerServer. Note that no peer-to-peer data goes through the server; The server acts only as a connection broker.

    It doesn't appear to be setup to handle direct communication with peers, however socket.io can.