目录
效果展示
关键代码
推流端这里创建Offer,创建成功之后然后通过socket.io发送到信令服务器,然后通过信令服务器转发
//启动一个新的WebRTC去连接远程端点
pc1.createOffer(offerOptions)
.then((desc)=>{
//设置本地Description
pc1.setLocalDescription(desc);
//设置远端Description(正常应该通过服务器发送给远端)
socket.emit("sendOffer",roomId,desc);
})
.catch();
服务器收到后直接转发
sokcetClient.on('sendOffer',(roomId,offerDesc)=>{
//收到Offer的Desc
console.log(offerDesc);
sokcetClient.in(roomId).emit('receiverOffer', offerDesc);
})
接收方收到信令服务器转发的Offer的时候设置RemoteDescription然后创建Answer并发送
socket.on("receiverOffer",(offerDesc)=>{
console.log(offerDesc);
var offer = new RTCSessionDescription(offerDesc);
pc2.setRemoteDescription(offer);
pc2.createAnswer().then((desc2)=>{
//设置本地Description
pc2.setLocalDescription(desc2);
socket.emit("sendAnswer",roomId,desc2);
}).catch((e)=>{
console.error(e);
});
});
同样的服务器收到后转发
sokcetClient.on('sendAnswer',(roomId,answerDesc)=>{
//收到Answer的Desc
console.log(answerDesc);
sokcetClient.in(roomId).emit('receiverAnswer', answerDesc);
})
当发送端收到服务器转发的Answer的时候设置RemoteDescription
socket.on("receiverAnswer",(answerDesc)=>{
console.log(answerDesc);
pc1.setRemoteDescription(new RTCSessionDescription(answerDesc));
});
当触发RTCPeerConnection的onicecandidate的时候将candidate发送到信令服务器然后通过信令服务器转发
//收到候选者onicecandidate
pc1.onicecandidate = (event)=>{
//将新接收到的候选者传递给浏览器的ICE代理
//pc2.addIceCandidate(event.candidate);
console.log("pc1");
console.log(event.candidate);
socket.emit("candidate",roomId,{
label:event.candidate.sdpMLineIndex,
id:event.candidate.sdpMid,
candidate:event.candidate.candidate
});
}
服务器进行转发
sokcetClient.on('candidate',(roomId,data)=>{
console.log(data);
sokcetClient.in(roomId).emit('receiverCandidate', data);
})
收到服务器转发的candidate数据后给RTCPeerConnection设置Candidate
socket.on("receiverCandidate",(data)=>{
var candidate = new RTCIceCandidate({
sdpMLineIndex:data.label,
candidate:data.candidate
});
pc1.addIceCandidate(candidate);
});
另外注意创建RTCPeerConnection的时候配置好turn服务器,这里使用的是Google提供的公开的服务器
const iceConfiguration = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
}
var pc = new RTCPeerConnection(iceConfiguration);
网友评论