基于webRTC的前端远程控制系统

项目中需要做远程控制,可以传输指令和音频,领导说用前端做,整合到h5中,于是研究了一下webRTC,基本能解决需求.就把项目简化写了一个demo分享出来

初始化配置

核心就是两端通过内网nat穿透建立p2p连接,这里我将peerB作为主控端,初始化时,连接本机获取本地icecandidate,这里icecandidate可以理解为内网nat对外网的映射,可以直接在公网访问的地址,可以是一个公网域名,也可以是服务器ip+端口,获取之后,通过http传输给TURN中继服务器,由中继服务器转发给peerA,这里peerA和peerB由登录的用户组来控制,进行不同的初始化设置.

关键代码:
    // 监听 B 的ICE候选信息
   // 如果收集到,就添加给 A
      this.peerB.onicecandidate = (event) => {
        console.log("iceb", event);
        if (event.candidate) {
          //实际通信时,这里要用http把event.candidate发送给TURN中继服务器,由中继服务器转发给peerA
          this.peerA.addIceCandidate(event.candidate);
        }
      };

在socket初始化时,获取本地地址,进而换取icecandidate

import io from "socket.io-client";
let host = location.origin;
const socket = io.connect(host);

建立p2p连接

peerB作为主控端,主动发起连接,发出offer,设置本地LocalDescription和远端RemoteDescription,都是同一个offer标志,peerA接收到请求后回复answer,设置本地LocalDescription和远端RemoteDescription,都是同一个answer标志,此时连接完成,会自动调用peerA和peerB的onopen事件,可以进行双工通信

传输控制信令

信令格式可以自定义,我这里是简化demo,所以就简单的放置了clientX, clientY, type, target, innerText 五个参数,都是从鼠标事件中获取的,获取之后用相应的信道进行发送,远端注册相应的onmessage函数进行处理即可

监听dom的click时间,捕获鼠标事件进行发送
  clickB(e) {
      if (!this.channelB) return;
      const { clientX, clientY, type, target, innerText } = e;
      console.log("Btarget", target.getAttribute("id"));
      this.channelB.send(
        JSON.stringify({
          clientX,
          clientY,
          type,
          target: target.getAttribute("id"),
          innerText,
        })
      );
    },
远端注册onmessage函数,对消息进行处理
 this.channelA.onmessage = (e) => {
          let m = JSON.parse(e.data);
          if (m.type === "click") {
            this.receiveTextA = "A收到了点击" + m.target;
            this.$refs["a"].click();
          } else if (m.type === "msg") {
            this.receiveTextA = "A收到了消息" + m.sendText;
            this.show = false;
          } else {
            console.log("channelA onmessage", JSON.parse(e.data));
            this.receiveTextA = "A收到了" + e.data + "";
            if (!this.oldTopA || !this.oldLeftA) {
              this.oldTopA = m.clientY;
              this.oldLeftA = m.clientX;
              return;
            }
            this.insertValueA(m.clientY, m.clientX);
          }
        };

插值算法

鼠标事件不可连续发送,由于js线程和ui线程是互斥的,连续发送事件会造成ui阻塞,所以必须按一定的时间间隔进行发送鼠标位置

   updateXYB: function(event) {
      if (this.channelB.readyState !== "open") return;
      if (this.timerB) return;
      console.log("Bmove event", event);
      const { clientX, clientY, type, target, innerText } = event;
      this.timerB = setTimeout(() => {
        clearTimeout(this.timerB);
        this.timerB = null;
        this.channelB.send(
          JSON.stringify({ clientX, clientY, type, target, innerText })
        );
      }, 200);
    },

在接收端,设置一个old标志,第一次接收到数据并不绘制,保存起来,从第二次接收到数据开始与前一帧数据进行运算,插值绘制鼠标轨迹,可以有效提升性能.

     if (!this.oldTopB || !this.oldLeftB) {
            this.oldTopB = m.clientY;
            this.oldLeftB = m.clientX;
            return;
          }
    this.insertValueB(m.clientY, m.clientX);
插值函数,保证不卡顿
 insertValueA(y, x) {
      if (!this.topA || !this.leftA) {
        this.topA = this.oldTopA + "px";
        this.leftA = this.oldLeftA + "px";
        return;
      }
      let n = 9;
      let stepY = (y - this.oldTopA) / n;
      let stepX = (x - this.oldLeftA) / n;
      let insertValueATimer = setInterval(() => {
        this.topA = +this.topA.slice(0, this.topA.indexOf("px")) + stepY + "px";
        this.leftA =
          +this.leftA.slice(0, this.leftA.indexOf("px")) + stepX + "px";
        n--;
        if (n === 0) {
          clearInterval(insertValueATimer);
          insertValueATimer = null;
        }
      }, 20);

      this.oldTopA = y;
      this.oldLeftA = x;
    },

以上就是webRtc信令传输实现远程控制的基本思路,音频也是类似,当p2p通道建立起来之后,整个连接可以复用多条udp连接,直接进行音频推送就可以实现语音和鼠标控制事件同时发送给被控端了

demo地址: https://github.com/gusuziyi/Remote-control.git

你可能感兴趣的:(基于webRTC的前端远程控制系统)