测试coturn服务器是否可用(Webrtc)
我们在使用webrtc 做视频连接的时候,如果涉及到不同网络之间的通信,往往会用到turn server来做视频中转。
我们在使用webrtc 做视频连接的时候,如果涉及到不同网络之间的通信,往往会用到turn server来做视频中转,google也为我们提供了开源的turn server 源码,但是搭建成功后,如何能知道是否能正常使用呢?我们需要一个demo来做简单测试:
function checkTURNServer(turnConfig, timeout){
return new Promise(function(resolve, reject){
setTimeout(function(){
if(promiseResolved) return;
resolve(false);
promiseResolved = true;
}, timeout || 5000);
var promiseResolved = false
, myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection //compatibility for firefox and chrome
, pc = new myPeerConnection({iceServers:[turnConfig]})
, noop = function(){};
pc.createDataChannel(""); //create a bogus data channel
pc.createOffer(function(sdp){
if(sdp.sdp.indexOf('typ relay') > -1){ // sometimes sdp contains the ice candidates...
promiseResolved = true;
resolve(true);
}
pc.setLocalDescription(sdp, noop, noop);
}, noop); // create offer and set local description
pc.onicecandidate = function(ice){ //listen for candidate events
if(promiseResolved || !ice || !ice.candidate || !ice.candidate.candidate || !(ice.candidate.candidate.indexOf('typ relay')>-1)) return;
promiseResolved = true;
resolve(true);
};
});
}
checkTURNServer({
url: 'turn:*.*.*.*',
username: '×××××××',
credential: '××××××××××',
}).then(function(bool){
console.log('is my TURN server active? ', bool? 'yes':'no');
}).catch(console.error.bind(console));
通过执行 checkTURNServer 方法,根据返回值判断是否连接成功。
很赞哦! ( 0
)