Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of connected users in PeerJS server (with express)?

I'm trying to use PeerJS (a webRTC library) for a game and triyng to use the server they provide for doing user discovery. I want to manage a list of connected users and I'm struggling with PeerJS server.

In the doc they say we can have a PeerJs and an Express server in the same app.

Here is the code :

// this doesn't work
var express = require('express');
var app = express();
var ExpressPeerServer = require('peer').ExpressPeerServer;

app.get('/', function(req, res, next) { res.send('Hello world!'); });

var server = app.listen(9000);

var options = {
    debug: true,
    allow_discovery: true
}

app.use('/api', ExpressPeerServer(server, options));

server.on('connection', function(id) {
    // we get a socket object as id :( 
    // should be a string
    console.log(id)
});

server.on('disconnect', function(id) { console.log(id + "deconnected") });

Nevertheless, when a user connects, I get a socket object as id, which is not what I want. Also I can't access to the connected peers at the url http://localhost:9000/peerjs/peers


What is strange is that, using only PeerJS server, it works as expected (I get the string ID of the peer), and I can access to the connected peers at the url http://localhost:9000/peerjs/peers.

// this works 
var ip = require('ip');
var PeerServer = require('peer').PeerServer;

var port = 9000;
var server = new PeerServer({port: port, allow_discovery: true});

server.on('connection', function (id) {
  // id is correct (a string)
  console.log('new connection with id ' + id);
});

server.on('disconnect', function (id) {
  console.log('disconnect with id ' + id);
});

console.log('peer server running on ' +
            ip.address() + ':' + port);

Any clues to make PeerJS server work with express ? Is it a regression about the express compatibility ?

Thanks a lot :)


System infos :

  • node -v : v0.10.25
  • Ubuntu 14.04
  • peerJS server installed from github with : npm install peers/peerjs-server (version: "0.2.8")
like image 588
ice3 Avatar asked Oct 29 '25 00:10

ice3


2 Answers

var app = express();
var server = app.listen(8000);
var q = ExpressPeerServer(server, options);
app.use('/peer', q);
q.on('connection', function (id) {
    console.log('user with ', id, 'connected');
});

this should work

like image 85
mutant_america Avatar answered Oct 31 '25 15:10

mutant_america


Just incase anyone having same issue all you need to do is:

server.on('disconnect', function (client) 
{
    // this will give you id in text or whatever format you are using
    console.log('disconnect with id ' + client.id);
});
like image 31
Syed Shahzaib Avatar answered Oct 31 '25 15:10

Syed Shahzaib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!