<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>P2P Chat</title>
<style>
#voip{
display:grid;
grid-template-columns: 1fr 1fr;
gap:1em;
}
#p1,#p2{
background-color:black;
width:100%;
}
</style>
</head>
<body>
<div id="voip">
<video id="p1" autoplay muted playsinline></video>
<video id="p2" autoplay controls muted playsinline></video>
</div>
<script src="agora-rtm-sdk-1.4.4.js"></script>
<script src="server.js"></script>
</body>
Here is server.js code
try {
let sid = String(Math.floor(Math.random() * 1e5)),
ls, rs, pc, ws, room, pid, poff, m1, ice;
alert(sid);
const config = { offerToReceiveAudio: true, offerToReceiveVideo: true },
ng = navigator,
id = x => document.getElementById(x),
pp = id('p2'),
i = [
'Connection state changed:',
'Logged in...',
'Joined channel',
'Failed to join channel',
'Failed to login: ',
'Message received: ',
'Your Offer: ',
'Your Answer: '
],
io = (x, y, z = '') => console.log(i[parseInt(x)], y, 'Reason:', z);
let init = async () => {
await ng.mediaDevices.getUserMedia({ audio: false, video: true }).then(async (s) => {
`
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>P2P Chat</title>
<style>
#voip{
display:grid;
grid-template-columns: 1fr 1fr;
gap:1em;
}
#p1,#p2{
background-color:black;
width:100%;
}
</style>
</head>
<body>
<div id="voip">
<video id="p1" autoplay muted playsinline></video>
<video id="p2" autoplay controls muted playsinline></video>
</div>
<script src="agora-rtm-sdk-1.4.4.js"></script>
<script src="server.js"></script>
</body>
`
Here is server.js code
`
try {
let sid = String(Math.floor(Math.random() * 1e5)),
ls, rs, pc, ws, room, pid, poff, m1, ice;
alert(sid);
const config = { offerToReceiveAudio: true, offerToReceiveVideo: true },
ng = navigator,
id = x => document.getElementById(x),
pp = id('p2'),
i = [
'Connection state changed:',
'Logged in...',
'Joined channel',
'Failed to join channel',
'Failed to login: ',
'Message received: ',
'Your Offer: ',
'Your Answer: '
],
io = (x, y, z = '') => console.log(i[parseInt(x)], y, 'Reason:', z);
let init = async () => {
console.log("Initializing user media...");
await ng.mediaDevices.getUserMedia({ audio: false, video: true }).then(async (s) => {
console.log("User media initialized");
ls = s;
id('p1').srcObject = s;
await off();
}).catch(e => alert(`getUserMedia error: ${e.message}`));
};
let off = async () => {
pc = new RTCPeerConnection({
iceServers: [
{ urls: ['stun:stun1.l.google.com:19302', 'stun:stun2.l.google.com:19302'] }
]
});
pc.addEventListener('connectionstatechange', e => {
console.log('Connection state change:', pc.connectionState);
if (pc.connectionState === 'connected') {
console.log('Peer connected!');
} else if (pc.connectionState === 'failed') {
console.error('Connection failed. Investigate the ICE candidates and network setup.');
}
});
pc.onicecandidate = async (e) => {
if (e.candidate) {
console.log('New ICE candidate:', e.candidate);
ice = e.candidate;
} else {
console.log('ICE candidate gathering complete');
}
};
ls.getTracks().forEach(t => {
console.log('Adding local track:', t);
pc.addTrack(t, ls);
});
pc.ontrack = tks => {
console.log('Received remote track:', tks);
if (!rs) {
rs = new MediaStream();
pp.srcObject = rs;
}
tks.streams[0].getTracks().forEach(tk => {
console.log('Adding track to remote stream:', tk);
rs.addTrack(tk);
});
};
poff = await pc.createOffer(config);
console.log('Created offer:', poff);
await pc.setLocalDescription(poff);
ws = AgoraRTM.createInstance('84a1a61490d642ceb93c9c1ebd796dbf');
ws.on('ConnectionStateChanged', (s, r) => io(0, s, r));
await ws.login({ token: null, uid: sid }).then(async () => {
io(1, id);
room = ws.createChannel('main');
await room.join().then(() => {
console.log('Joined channel');
room.on('MemberJoined', async (pi) => {
pid = pi;
console.log('Member joined, exchanging ICE candidates...');
await ws.sendMessageToPeer({ text: JSON.stringify({ 'type': 'offer', 'offer': poff, 'pid': sid }) }, pid)
.then(async () => {
console.log('Offer sent');
await ws.sendMessageToPeer({ text: JSON.stringify({ 'type': 'ice', 'ice': ice }) }, pid)
.then(() => console.log('ICE Candidates exchanged'))
.catch(e => console.error('ICE Candidates exchange failed!', e));
}).catch(e => console.error('Offer exchange failed!', e));
});
ws.on('MessageFromPeer', async (m, ii) => {
m1 = JSON.parse(m.text);
let mo = m1.offer || m1.answer || m1.ice;
io(5, mo, ' LATEST ');
if ('ice' === m1.type) {
console.log('Received ICE candidate:', mo);
await pc.addIceCandidate(new RTCIceCandidate(mo)).then(() => {
console.log('ICE candidate successfully added.');
}).catch(error => {
console.error('Error adding ICE candidate:', error);
});
}
if ('offer' === m1.type) {
console.log('Received offer:', mo);
await pc.setRemoteDescription(mo);
let ans = await pc.createAnswer(config);
io(7, ans, ii);
await pc.setLocalDescription(ans);
await ws.sendMessageToPeer({ text: JSON.stringify({ 'type': 'answer', 'answer': ans, 'pid': ii }) }, m1.pid);
} else if ('answer' === m1.type) {
console.log('Received answer:', mo);
await pc.setRemoteDescription(new RTCSessionDescription(mo));
}
});
}).catch(e => io(3, e));
}).catch(e => io(4, id));
};
init();
} catch (e0) {
alert(e0);
}
`
```Additionally, I've attached the screenshots of the console screen. The issue that peer video is not displaying.... I've used Agora RTM as signalling server. Only issue with handling tracks, I think so ...```
Troubleshoot the issue and desired peer video[](https://i.sstatic.net/19xT2IH3.jpg)
Additionally, I’ve attached the screenshots of the console screen. As per console, ICECandidates are exchanged. The issue that peer video is not displaying…. I’ve used Agora RTM as signalling server. Only issue with handling tracks, I think so …
Troubleshoot the issue and desired peer video[](https://i.sstatic.net/19xT2IH3.jp
g)