- internals.socket.on('disconnect', function() {
-
- console.log("disconnected from signaling server");
- });
-
- internals.socket.on('addPeer', function(data) {
-
- Peers.add(data.peerId, internals.tada);
- const peerId = data.peerId;
-
- const peerConnection = new RTCPeerConnection(
- { iceServers: internals.kIceServers },
- { optional: [{ DtlsSrtpKeyAgreement: true }] }
- );
-
- internals.peers[peerId] = peerConnection;
- mediaStream.getTracks().forEach((track) => {
- peerConnection.addTrack(track, localStream);
- });
-
- peerConnection.onicecandidate = (event) => {
- if (event.candidate) {
- internals.socket.emit('relayICECandidate', {
- peerId: peerId,
- candidate: event.candidate
- });
- }
- }
-
- const remoteStream = new MediaStream();
- peerConnection.ontrack = (event) => {
- remoteStream.addTrack(event.track);
- const remoteAudioElement = new Audio();
- remoteAudioElement.srcObject = remoteStream;
- remoteAudioElement.play();
- };
-
- peerConnection.onnegotiationneeded = async () => {
- console.log("Creating RTC offer to ", peerId);
- const offer = await peerConnection.createOffer();
- await peerConnection.setLocalDescription(offer);
-
- // Emit the offer to the peer
- socket.emit('relayOffer', { offer, peerId });
- };
-
- console.log(`There are now ${Peers.count()} participants`);
- });
-
- socket.on('offerReceived', async (data) => {
-
- const peerConnection = internals.peers[data.peerId];
-
- const offer = new RTCSessionDescription(data.offer);
- await peerConnection.setRemoteDescription(offer);
-
- const answer = await peerConnection.createAnswer();
- await peerConnection.setLocalDescription(answer);
-
- // Send the answer to the peer
- socket.emit('relayAnswer', { answer, peerId: data.peerId });