【发布时间】:2020-05-05 20:15:07
【问题描述】:
我正在尝试使用 WebRTC 和 SocketIO 构建一个简单的 p2p 视频通话以进行消息传递。当两个客户端连接到不同的 WIFI 网络时,视频聊天工作正常,但是当其中一个客户端使用移动热点时,无法建立连接。以下是一些可能有助于发现问题的关键代码块: 开始通话/createOffer
function callNeighbor(){
if(buddy=={}){console.log('CALL_NEIGHBOR Neighbor NULL')}
else{
const servers = {iceServers: [{urls: 'stun:stun1.l.google.com:19305'}]};
pc=new RTCPeerConnection(servers);
pc.onicecandidate = e => onIceCandidate(pc, e);
pc.ontrack=gotRemoteStream;
pc.onnegotiationneeded=function(){
pc.createOffer().then(success=>{
console.log(success)
pc.setLocalDescription(success).then(success=>{
socket.emit('rtcRequest',{from:name,to:buddy.name,body:pc.localDescription});
},error=>{
console.log(failure);
});
},
failure=>{
console.log(failure);
})
}
navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError);
}
}
onICECandidate
function onIceCandidate(pc, event) {
const candidate=event.candidate
if(candidate==null){return}
console.log('**SENDING ICE** '+candidate)
console.log(candidate)
socket.emit("rtcICE",{from:name,to:buddy.name, body:candidate});
console.log(`PC ICE candidate:\n${candidate ? candidate.candidate : '(null)'}`);
}
接听电话/createAnswer
function handleCall(stream) {
console.log(stream);
localOut.srcObject = stream;
localStream = stream;
const audioTracks = localStream.getAudioTracks();
if (audioTracks.length > 0) {
// console.log(`Using Audio device: ${audioTracks[0].label}`);
}
localStream.getTracks().forEach(track => pc.addTrack(track, localStream));
// console.log('Adding Local Stream to peer connection');
pc.createAnswer().then(answer=>{
pc.setLocalDescription(answer).then(success=>{
socket.emit('rtcResponse',{from:name,to:buddy.name,body:pc.localDescription});
},error=>{console.log(error)})
},error=>{console.log(error)})
}
添加 Ice Candidate
socket.on('rtcICE',function(data){//rtcICE is via socketIO see onICECandidate above
pc.addIceCandidate((data.body)).then(success=>console.log(success),error=>console.log(error));
})
日志
来电者
编辑这是设置远程描述的代码
socket.on('rtcRequest',function(data){
const offer=data.body;
const servers = {iceServers: [{urls: 'stun:stun1.l.google.com:19305'}]};;
pc=new RTCPeerConnection(servers);
pc.onicecandidate = e => onIceCandidate(pc, e);
pc.ontrack=gotRemoteStream;
pc.onnegotiationneeded=function(){
console.log('NEGOTIATION NEEDED!!!')}
pc.setRemoteDescription(data.body).then(success=>{
navigator.mediaDevices.getUserMedia(constraints).then(handleCall).catch(handleError);
},
error=>{console.log(error)
}
);
})
【问题讨论】:
-
接收端什么时候执行setRemoteDescription()?
-
@kenjitanaka 刚刚添加到底部
-
更新,代码在 2 个不同的 wifi 网络上工作,但在移动热点上中断
-
在onnegotiationneeded事件中不要做setRemoteDescription()。
-
我不是,抱歉格式错误,onnegotiationneeded 只是控制台日志“NEGOTIATION NEEDED”;我只是想看看它什么时候着火,所以我添加了那个日志