I spent my whole day trying to set up my app using peer but couldn't succeed so far.
Here's what my server js file looks like:
const path = require('path');
const express = require('express');
const { ExpressPeerServer } = require('peer');
const app = express();
const PORT = process.env.PORT || 3000;
// set your static server
app.use(express.static(path.resolve(`${__dirname}/public`)));
// views
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'views/index.html'));
});
// start listening
const server = app.listen(PORT);
console.log('Server is running localhost on port: ' + PORT);
// peerjs
const peerServer = ExpressPeerServer(server, {
debug: true,
});
app.use('/peerjs', peerServer);
// listeners
peerServer.on('connection', (client) => {
console.log("Server: Peer connected with ID:", client.id);
});
peerServer.on('disconnect', (client) => {
console.log("Server: Peer disconnected with ID:", client.id);
});
When I run the app, it says Server: Peer connected with ID: ff1b23c0-9b67-49e3-8461-35405397d3b2
but then a minute later it says Server: Peer disconnected with ID: ff1b23c0-9b67-49e3-8461-35405397d3b2
.
Also, I failed to make the server connect to the client. The peer.on('connection', function(conn) {}
function never gets called. I may be missing something.
So I'm trying to find an example code that works but so far I haven't found any example(using nodeJS, express, peerJS) that works.
Can anyone please introduce me to any working example of a node app that uses peer?
All I want is just to check the server-client connection as a first step. (without the connection being disconnected automatically)
Here is a small working example, I have tried this myself.
Your backend Express Server:
const express = require('express');
const { ExpressPeerServer } = require('peer');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/', (req, res, next) => res.send('Hello world!'));
const server = app.listen(9000);
const peerServer = ExpressPeerServer(server, {
debug: true
});
app.use('/peerjs', peerServer);
peerServer.on('connection', (client) => { console.log('client connected');});
peerServer.on('disconnect', (client) => { console.log('client disconnected');});
And your frontend code to connect with above peer server:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/peerjs@0.3.20/dist/peer.min.js"></script>
</head>
<body>
<script>
const peer = new Peer('someid', {
host: 'localhost',
port: 9000,
path: '/peerjs'
});
</script>
</body>
</html>