WebRTC Peer Track not displaying after Ice candidates exchanged. JavaScript


<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[![present output](https://i.sstatic.net/19xT2IH3.jpg)](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[present output](https://i.sstatic.net/19xT2IH3.jp
g)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật