我正在使用Socket.IO构建一个WebRTC应用程序作为我的信号。
我假设同时只有两个客户端会成为页面(这就是我跳过大量验证的原因),我只是想直接进入WebRTC。
应用程序运行正常,唯一的问题是,为了使其工作,两个客户端之一必须刷新页面。
我要做的是,第二个客户将是第一个客户。
第一个客户进入页面,他只能看到自己,当第二个客户进入时,然后开始交换描述。这很好,(我确实登录到控制台,似乎一切都在发生,因为它应该发生)。
就像我说的那样,唯一的问题是当第二个客户端进入时,其中一个必须刷新页面才能看到两个视频流。
这是我的代码:
var socket = io.connect(window.location.host);
var peerConf = {
"iceServers": [{
"url": "stun:stun3.l.google.com:19302"
}]
};
var peerConnection = new RTCPeerConnection(peerConf);
peerConnection.onicecandidate = (event) => {
if(event.candidate != null) {
socket.emit('answerer', {
type: 'ice',
candidate: event.candidate
});
} else {
console.log("All ICE Candidates have been received and sent to the other peer.");
}
};
var startCall = (isCaller) => {
if(isCaller) {
peerConnection.createOffer()
.then((desc) => {
peerConnection.setLocalDescription(desc)
.then(() => {
console.log("Local description has been set successfully!");
socket.emit('caller', {
type: 'sdp',
description: desc
});
})
.catch((errLocal) => {
console.log("Error setting local description: \n" + errLocal);
});
})
.catch((errOffer) => {
console.log("Error creating offer: \n" + errOffer);
});
}
};
navigator.getUserMedia({
//audio: true,
video: true
}, (stream) => {
var localvideo = document.getElementById('localVideo');
var remoteVideo = document.getElementById('remoteVideo');
localvideo.src = window.URL.createObjectURL(stream);
peerConnection.addStream(stream);
peerConnection.onaddstream = (eventRemoteStream) => {
remoteVideo.src = window.URL.createObjectURL(eventRemoteStream.stream);
};
}, (err) => {
console.log("An error has occured: " + err);
});
socket.on('connected', (data) => {
console.log(data.message);
// The second client to connect will be the caller.
if(data.clients == 2) {
startCall(true);
}
});
socket.on('answering', (data) => {
switch(data.type) {
case 'sdp':
peerConnection.setRemoteDescription(new RTCSessionDescription(data.description))
.then(() => {
console.log("Connection has been established successfully! :D");
})
.catch((errRemoteAnswering) => {
console.log("Error setting remote description on answering: \n" + errRemoteAnswering);
});
break;
case 'ice':
peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
break;
}
});
socket.on('calling', (data) => {
switch(data.type) {
case 'sdp':
peerConnection.setRemoteDescription(new RTCSessionDescription(data.description))
.then(() => {
if(data.description.type == 'offer') {
peerConnection.createAnswer()
.then((answerDesc) => {
peerConnection.setLocalDescription(answerDesc)
.then(() => {
socket.emit('answerer', {
type: 'sdp',
description: answerDesc
});
})
.catch((errLocalAns) => {
console.log("Error setting local description on answering: \n" + errLocalAns);
});
})
.catch((errAnswer) => {
console.log("Error creating answer: \n" + errAnswer);
});
}
})
.catch((errRemote) => {
console.log("Error setting remote description on calling: \n" + errRemote);
});
break;
}
});
我不知道我是否遗漏了某些东西,或者是否有东西放在不应该的地方。
我真的希望你们能帮助我。 提前致谢。 :)