使用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>
发表评论: