WebRTC peerConnection 'icecandidate' 事件侦听器不起作用

时间:2021-04-03 21:50:55

标签: javascript reactjs socket.io webrtc

我正在尝试使用 socket.io 和此文档建立 webRTC 连接:https://webrtc.org/getting-started/peer-connections。看起来我已经能够建立连接并设置 LocalDescription 和 Remote Description,但是 'icecandidate' 事件侦听器永远不会触发将候选人添加到另一个。任何帮助将不胜感激!

客户

const peerConnection = new RTCPeerConnection(config);
const config = {
    iceServers: [{ "urls": "stun:stun.l.google.com:19302", }]
};

async function makeCall() {

  const offer = await peerConnection.createOffer();
  await peerConnection.setLocalDescription(offer);

  socket.emit('offer', (offer));

  socket.on('answer', async (answer) => {
    if(answer) {
      console.log("answer successful");
      const remoteDesc = new RTCSessionDescription(answer);
      await peerConnection.setRemoteDescription(remoteDesc);
      console.log(peerConnection);

    }
  });
}

makeCall();

socket.on('offer', async (offer) => {
  if(offer) {
    console.log("now sending offer: " + offer);
    peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
    const answer = await peerConnection.createAnswer();
    await peerConnection.setLocalDescription(answer);
    socket.emit('answer', (answer));
    //signalingChannel.send({'answer': answer});
  }
});
    
// !!! THIS CODE NEVER TRIGGERS AND 'peerConnection.iceCandidate' returns null
peerConnection.addEventListener('icecandidate', event => {
  console.log('triggered outside scope'); // trigger check
    if (event.candidate) {
        console.log('triggered inside scope'); // trigger check
        socket.emit('candidate', event.candidate);
    }
});


// BELOW WILL NOT TRIGGER WITHOUT 'icecandidate' LISTENER

// Listen for remote ICE candidates and add them to the local RTCPeerConnection ()
socket.on('candidate', async (iceCandidate) => {
    if (iceCandidate) {
        try {
            await peerConnection.addIceCandidate(iceCandidate);
        } catch (e) {
            console.error('Error adding received ice candidate', e);
        }
    }
  })

// Confirm they are connected
peerConnection.addEventListener('connectionstatechange', event => {
    if (peerConnection.connectionState === 'connected') {
        // Peers connected!
        console.log('success')
    }
});
            

服务器

io.on("connection", (socket) => {
    

  socket.on('offer', (offer, answer) => {
    console.log(offer);
    socket.broadcast.emit('offer', (offer));
  }) 

  socket.on('answer', (answer) => {
    console.log(answer);
    socket.broadcast.emit('answer', (answer));
  }) 

  socket.on('candidate', (candidate) => {
    console.log(candidate);
    socket.broadcast.emit('candidate', (candidate));
  }) 

});

1 个答案:

答案 0 :(得分:0)

您尝试建立的连接没有任何媒体轨道(通过 addTrack 或 addTransceiver 添加)或数据通道。因此,您的报价将不会有任何 SDP m= 行,并且由于 ice 候选者与您不会得到的那些相关联,因此不会建立任何连接。