我正在尝试做一个视频会议应用,所有的对等体连接在一个网状物中,我正在做的是当一个对等体加入房间时,他们向在场的每一个人广播他们的ID,每个人都用这个ID向广播者回电,有时它能够连接到每一个人,但其他时候,广播者收到了所有的提议,但只发回一些答案,跳过其他提议。有时其能够连接到每个人,但其他时候,广播者收到所有的提议,但只发送回一些答案,跳过其他提议。有没有办法用asyncawait来处理并逐一回传答案?我对javascript和WebRTC很陌生,试了很多东西,但都没弄明白。
处理报价的代码。
socket.on('message',function(message) {
if(message.type === 'offer') {
if(message.specific === clientId){
if(message.isSuperNode === false)
isNodeCap++;
createPeerConnection(message.userid,message.isSuperNode);
pc.peerConnection.addStream(pc.mixer.getMixedStream());
pc.peerConnection.setRemoteDescription(new RTCSessionDescription(message));
console.log("Offer Received");
localPeerList.push(pc);
doAnswer(message.userid);
}
});
function createPeerConnection(userid,isSN) {
try {
var obj ={};
obj.peerConnection = new RTCPeerConnection(pcConfig);
obj.mixer = new MultiStreamsMixer([localStream]);
obj.mixer.startDrawingFrames();
obj.connectionWith = userid;
obj.isSuperNode = isSN;
obj.peerConnection.onicecandidate = handleIceCandidate
obj.peerConnection.onaddstream = handleRemoteStreamAdded;
obj.peerConnection.onremovestream = handleRemoteStreamRemoved;
pc = Object.assign({},obj);
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
return;
}
}
function doAnswer(userid) {
console.log('Sending answer to peer.');
pc.peerConnection.createAnswer().then(function(offer){
pc.peerConnection.setLocalDescription(offer).then(function(){
answering = true;
}
).catch(function(e) {
alert(e.name);
});
});
}
我不清楚你的例子中的语义,但是一个潜在的问题是 doAnswer
并不是 "等待"。
所以你可以尝试将消息处理程序做成异步,并等待 doAnswer
这样调用。
socket.on('message', async function(message) {
if(message.type === 'offer') {
if(message.specific === clientId){
if(message.isSuperNode === false)
isNodeCap++;
createPeerConnection(message.userid,message.isSuperNode);
pc.peerConnection.addStream(pc.mixer.getMixedStream());
pc.peerConnection.setRemoteDescription(new RTCSessionDescription(message));
console.log("Offer Received");
localPeerList.push(pc);
await doAnswer(message.userid);
}
});
async function doAnswer(userid) {
console.log('Sending answer to peer.');
const offer = await pc.peerConnection.createAnswer();
try {
await pc.peerConnection.setLocalDescription(offer);
answering = true;
}
catch(e) {
alert(e.name);
}
}