我正在尝试建立一个随机的连接系统。我有一个按钮可以启动连接,并为新的自动呼叫寻找新的对等方。但它是断断续续的,有时它工作得很好,有时我不知道了。
后端 - server.js
/** successful connection */
wss.on('connection', function (client) {
console.log("A new WebSocket client was connected.");
/** incomming message */
client.on('message', function (message) {
/** broadcast message to all clients */
var obj = JSON.parse(message);
if("callState" in obj) {
// New client, add it to the id/client object
// client.set('call_state') = 1
console.log("Recebeu mensagem!!!");
}else if("sdp" in obj || "ice" in obj) {
wss.broadcast(message, client);
}else{
console.log("Recebeu: "+message);
}
});
});
// broadcasting the message to all WebSocket clients.
wss.broadcast = function (data, exclude) {
console.log("Broadcasting message to all " + this.clients.length + " WebSocket clients.");
for(var i in this.clients) {
client = this.clients[i];
// don't send the message to the sender...
if (client === exclude) continue;
if (client.readyState === client.OPEN) client.send(data);
else console.error('Error: the client state is ' + client.readyState);
}
};
前端 - webrtc.js
/** button START */
function start(isCaller) {
peerConnection = new RTCPeerConnection(peerConnectionConfig);
peerConnection.onicecandidate = gotIceCandidate;
peerConnection.addStream(localStream);
if ('ontrack' in peerConnection) {
// WebRTC Spec, Firefox
peerConnection.ontrack = ontrack
} else {
// Chrome, etc. This can be removed once all browsers support `ontrack`
peerConnection.onaddstream = gotRemoteStream
}
if(isCaller) {
peerConnection.createOffer().then(createdDescription).catch(errorHandler);
}
}
function gotMessageFromServer(message) {
if(!peerConnection) start(false);
var signal = JSON.parse(message.data);
// Ignore messages from ourself
if(signal.uuid == uuid) return;
if(signal.sdp) {
peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp)).then(function() {
// Only create answers in response to offers
if(signal.sdp.type == 'offer') {
peerConnection.createAnswer().then(createdDescription).catch(errorHandler);
}
}).catch(errorHandler);
} else if(signal.ice) {
peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler);
}
}
在服务器日志中显示,每次我按下“开始”按钮时,它都会记录 1 条 SDP 消息和 14 条 ICE 消息
编辑:包括错误
当我第一次调用“开始”按钮时,一切正常。但是,在接下来的通话中,有时仅保留音频功能,而有时则没有新的连接。
多次单击“开始”后,我能够重现错误:DOMException [InvalidStateError:“无法在稳定状态下设置远程答案”代码:11 nsresult:0x8053000b]
我有一个本地服务器在运行:https ://luisdemarchi.aplicativo.info:8091