构建自己peerjs服务器
服务器.js
var express = require('express');
var app = express();
// create express peer server
var ExpressPeerServer = require('peer').ExpressPeerServer;
var options = {
debug: true
}
// create a http server instance to listen to request
var server = require('http').createServer(app);
// peerjs is the path that the peerjs server will be connected to.
const peerServer = ExpressPeerServer(server, options);
app.use('/peerjs', peerServer);
// Now listen to your ip and port.
server.listen(443, "192.168.2.18");
peerServer.on('connection', (client) => {
console.log('connection:'+client.getId());
});
peerServer.on('disconnect', (client) => {
console.log('disconnect:'+client.getId());
});
终端JS
function initialize() {
peer = new Peer({
host: '192.168.2.18',
port: 443,
path: '/peerjs',
config: { 'iceServers': [
{ url: 'stun:stun01.sipphone.com' },
{ url: 'stun:stun.ekiga.net' },
{ url: 'stun:stunserver.org' },
{ url: 'stun:stun.softjoys.com' },
{ url: 'stun:stun.voiparound.com' },
{ url: 'stun:stun.voipbuster.com' },
{ url: 'stun:stun.voipstunt.com' },
{ url: 'stun:stun.voxgratia.org' },
{ url: 'stun:stun.xten.com' },
{
url: 'turn:192.168.191.128:3478',
credential: 'password1',
username: 'user1'
},
]
},
debug: 3
});
peer.on('open', function (id) {
// Workaround for peer.reconnect deleting previous id
if (peer.id === null) {
console.log('Received null id from peer open');
peer.id = lastPeerId;
} else {
lastPeerId = peer.id;
}
console.log('ID: ' + peer.id);
});
peer.on('connection', function (c) {
// Disallow incoming connections
c.on('open', function() {
c.send("Sender does not accept incoming connections");
setTimeout(function() { c.close(); }, 500);
});
});
peer.on('disconnected', function () {
status.innerHTML = "Connection lost. Please reconnect";
console.log('Connection lost. Please reconnect');
// Workaround for peer.reconnect deleting previous id
peer.id = lastPeerId;
peer._lastServerId = lastPeerId;
peer.reconnect();
});
peer.on('close', function() {
conn = null;
status.innerHTML = "Connection destroyed. Please refresh";
console.log('Connection destroyed');
});
peer.on('error', function (err) {
console.log(err);
alert('' + err);
});
};
iceServers 服务器搭建