我尝试从Webrtc.org peerconnection guide实现 webrtc 代码。虽然没有生成有效的候选冰。我还注意到在 sdp 中总是使用 localhost ip (127.0.0.1),即使我在不同的设备上运行应用程序也是如此。在 Firefox 中,我确实收到了一个 icecandidate 事件。虽然 event.candidate == null。
有什么我做错了吗?
这是代码:
let socket = io()
let localStream = null;
const configuration = {
'iceServers': [{
'urls': 'stun:stun.l.google.com:19302'
}]
}
let peerConnection = new RTCPeerConnection(configuration)
// init video media
function start() {
navigator.mediaDevices.getUserMedia({
audio: true,
video: true
}).then(stream => {
localVideo.srcObject = stream
localStream = stream
})
for (let track of localStream.getTracks()) {
peerConnection.addTrack(track, localStream)
}
}
// starts the call
async function call() {
const offer = await peerConnection.createOffer()
await peerConnection.setLocalDescription(offer)
socket.emit('offer', offer)
}
peerConnection.onicecandidate = event => {
if (event.candidate) {
socket.emit('newIceCandidate', event.candidate)
}
}
// Listen for remote ICE candidates and add them to the local RTCPeerConnection
socket.on('newIceCandidate', async candidate => {
try {
await peerConnection.addIceCandidate(candidate)
} catch (e) {
console.log(e)
}
})
// Is never called
peerConnection.addEventListener('connectionstatechange', event => {
if (peerConnection.connectionState === 'connected') {
console.log('CONNECTED PEER')
}
})
// user 1 receiving data from other
socket.on('answer', async remoteDescription => {
const remoteDesc = new RTCSessionDescription(remoteDescription)
await peerConnection.setRemoteDescription(remoteDesc)
})
// user 2 getting init message
socket.on('offer', async offer => {
peerConnection.setRemoteDescription(new RTCSessionDescription(offer))
const answer = await peerConnection.createAnswer()
await peerConnection.setLocalDescription(answer)
socket.emit('answer', answer)
})
/////////////// Less relevant /////////////////
peerConnection.oniceconnectionstatechange = state => {
console.log('ice state change!')
}
peerConnection.ontrack = ({
streams: [stream]
}) => remoteVideo.srcObject = stream
function stop() {
}
start()