mirror of
https://gitlab.com/comunic/nodejs-webrtcsignalexchangerserver
synced 2024-11-22 05:19:26 +00:00
114 lines
2.7 KiB
JavaScript
114 lines
2.7 KiB
JavaScript
/**
|
|
* Node Signal Exchanger test client
|
|
*
|
|
* @author Pierre HUBERT
|
|
*/
|
|
|
|
function byId(id){
|
|
return document.getElementById(id);
|
|
}
|
|
|
|
const Config = {
|
|
port: 8081,
|
|
server_name: "localhost",
|
|
clientID: location.href.toString().includes("#1") ? "client-1" : "client-2",
|
|
otherPeerID: location.href.toString().includes("#1") ? "client-2" : "client-1"
|
|
};
|
|
|
|
let client = new SignalExchangerClient(
|
|
Config.server_name,
|
|
Config.port,
|
|
Config.clientID
|
|
);
|
|
|
|
let peer;
|
|
let localStream;
|
|
|
|
client.onConnected = function(){
|
|
console.log("Connected to signal exchanger server.");
|
|
|
|
InitializeVideo();
|
|
}
|
|
|
|
client.onError = function() {
|
|
console.error("An error occurred with the connection to the signal exchanger server");
|
|
}
|
|
|
|
client.onClosed = function() {
|
|
console.log("Connection to server closed.");
|
|
}
|
|
|
|
client.onSignal = function(signal, peerID){
|
|
|
|
if(peerID !== Config.otherPeerID)
|
|
return alert("A signal from an unknow peer ID has just been received!");
|
|
|
|
peer.signal(JSON.parse(signal));
|
|
|
|
|
|
}
|
|
|
|
function InitializeVideo(){
|
|
|
|
navigator.mediaDevices
|
|
.getUserMedia({
|
|
audio: true,
|
|
video: true
|
|
})
|
|
.then(stream => {
|
|
localStream = stream;
|
|
|
|
InitializePeer();
|
|
|
|
//Play local video
|
|
let video = byId("localVideo");
|
|
video.srcObject = stream;
|
|
video.play();
|
|
})
|
|
.catch(err => {
|
|
alert("Can not continue because you did not accept to share your camera!");
|
|
console.error(err);
|
|
});
|
|
|
|
}
|
|
|
|
/**
|
|
* Initialize peer connection
|
|
*
|
|
* Warning : It is better to wait for the socket connection to be ready before
|
|
* launching this function if this peer is the initiator of the connection
|
|
*/
|
|
function InitializePeer() {
|
|
|
|
peer = new SimplePeer({
|
|
initiator: location.hash === '#1',
|
|
stream: localStream,
|
|
trickle: false,
|
|
config: {
|
|
'iceServers': [
|
|
{ urls: 'stun:127.0.0.1:3478' },
|
|
{"url":"turn:127.0.0.1:3478",
|
|
"credential":"anonymous",
|
|
"username": "anonymous"}
|
|
]
|
|
}
|
|
});
|
|
|
|
peer.on('error', function (err) { console.log('SimplePeer error', err) });
|
|
|
|
//Automatically send new signals to the other peer
|
|
peer.on('signal', function (data) {
|
|
console.log('SIGNAL', JSON.stringify(data))
|
|
client.sendSignal(Config.otherPeerID, JSON.stringify(data));
|
|
});
|
|
|
|
peer.on("stream", stream => {
|
|
let video = byId("remoteVideo");
|
|
video.srcObject = stream;
|
|
video.play();
|
|
});
|
|
|
|
peer.on("message", message => {
|
|
console.log("Message from remote peer: " + message);
|
|
});
|
|
} |