我正在为这种风格的视频通话开发一个会议风格的应用程序(多对多)。该代码在 GitHub 上可用,但我没有太多 node.js 经验,因此我决定使用 PHP 创建自己的服务器。
我使用 WebSockets 创建了服务器。这很简单——它接收消息并将它们转发给所有其他连接的客户端(即,不是发送消息的客户端)。仅此而已-仅此而已;一点也不差。
但我的问题是这种架构不允许客户端与多个人连接,即,当客户端尝试与第三人连接时,附加流会失败。客户端只能一对一连接。
我不知道错误是在 JavaScript 中还是我需要改进服务器。我该怎么做才能使其连接到所有加入的客户?
查看我的代码:
HTML
<script type="text/javascript" src="http://127.0.0.1/scr/js/jquery.js"></script>
JavaScript
var Server = new WebSocket('ws://127.0.0.1:1805/'),
myStream = null,
peerConn = null,
mediaConstraints = {
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true
}
};
navigator.webkitGetUserMedia({
audio: true,
video: true
}, function(stream) {
myStream = stream;
$("body").append('<video width="320" height="240" muted="muted" autoplay="true" src="' + window.URL.createObjectURL(stream) + '"></video>');
createPeerConnection();
peerConn.addStream(myStream);
peerConn.createOffer(function(sessionDescription) {
peerConn.setLocalDescription(sessionDescription);
console.log("Sending offer description");
Server.send(JSON.stringify(sessionDescription));
}, null, mediaConstraints);
}, function() {
console.error('Error in my stream');
});
function createPeerConnection() {
console.log('Creating peer connection');
peerConn = new webkitRTCPeerConnection({
'iceServers': [{
'url': 'stun:stun.l.google.com:19302'
}, {
'url': 'turn:107.150.19.220:3478',
'credential': 'turnserver',
'username': 'subrosa'
}]
}, {
'optional': [{
'DtlsSrtpKeyAgreement': 'true'
}]
});
peerConn.onicecandidate = function(event) {
if (event.candidate) {
Server.send(JSON.stringify({
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
}));
} else {
console.error('Candidate denied');
}
};
peerConn.onaddstream = function(event) {
console.log("Adding remote strem");
$("body").append('<video width="320" height="240" autoplay="true" src="' + window.URL.createObjectURL(event.stream) + '"></video>');
};
peerConn.onremovestream = function(event) {
console.log("Removing remote stream");
};
}
Server.addEventListener("message", function(message) {
var msg = JSON.parse(message.data);
if(!myStream) {
console.error('Error in my stream');
}
if (msg.type === 'offer') {
createPeerConnection();
console.log('Adding local stream...');
peerConn.addStream(myStream);
peerConn.setRemoteDescription(new RTCSessionDescription(msg));
console.log("Sending answer to peer.");
peerConn.createAnswer(function(sessionDescription) {
peerConn.setLocalDescription(sessionDescription);
Server.send(JSON.stringify(sessionDescription));
}, null, mediaConstraints);
} else if (msg.type === 'answer') {
peerConn.setRemoteDescription(new RTCSessionDescription(msg));
} else if (msg.type === 'candidate') {
var candidate = new RTCIceCandidate({
sdpMLineIndex: msg.label,
candidate: msg.candidate
});
peerConn.addIceCandidate(candidate);
}
}, false);