测试coturn服务器是否可用(Webrtc)

这是一个用于检查coturn服务器是否适用于WebRTC的函数示例。通过创建RTCPeerConnection并监听icecandidate事件来查找' typ relay ',从而判断TURN服务器是否活跃。示例中还提供了使用示例,如果找到' typ relay ',则表明TURN服务器可用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值