检查turn服务器是否处于活跃状态

2019-5-24 Jon html+css

使用webRTC时

有时需要自己搭建turn服务器

如何测试搭建好的turn服务器是否可用

下面给出代码

修改checkTURNServer里面对象的

url/username/credential分别对应url/用户名/密码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>检查turn服务器是否处于活跃状态</title>
</head>
<body>
  <script>
    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,   // 兼容firefox和chrome
            pc = new myPeerConnection({iceServers:[turnConfig]}),
            noop = function(){};
        pc.createDataChannel("");    // 创建一个伪数据通道
        pc.createOffer(function(sdp) {
          if(sdp.sdp.indexOf('typ relay') > -1){ // 有时sdp包含ice候选项…
            promiseResolved = true;
            resolve(true);
          }
          pc.setLocalDescription(sdp, noop, noop);
        }, noop);    // 创建报价并设置本地描述
        pc.onicecandidate = function(ice){  // 监听候选事件
          if(promiseResolved || !ice || !ice.candidate || !ice.candidate.candidate || !(ice.candidate.candidate.indexOf('typ relay')>-1))  return;
          promiseResolved = true;
          resolve(true);
        };
      });
    }
    checkTURNServer({
      url: 'turn:53.83.181.100:3478',
      username: '1232131311:abc',
      credential: 'sfffqwerfwef3243524fx='
    }).then(function(bool){
      console.log('is my TURN server active? ', bool? 'yes':'no');
    }).catch(console.error.bind(console));
  </script>
</body>
</html>


标签: webRTC

分享这篇文章
赞助鼓励:如果觉得内容对您有所帮助,您可以支付宝(左)或微信(右):

声明:如无特殊注明,所有博客文章版权皆属于作者,转载使用时请注明出处。谢谢!

发表评论:

皖ICP备15010162号-1 ©2015-2022 知向前端
qq:1614245331 邮箱:13515678147@163.com Powered by emlog sitemap