实时通信socket封装及使用

使用场景--实时通信

1.封装socket

//socket连接
export function connectSocket(data){
    return new Promise(function(resolve){
        let that = this;
        let ws = new WebSocket('xxxxx');//通信地址
        ws.onopen = function (e) {
            // 登录socket所需的参数
            ws.send(xxxxx);
        }
        ws.onmessage = function (e) {
            console.log('ws 连接开启');
            resolve(ws);
        }
        ws.onclose = function (e) {
            console.log('ws 连接关闭了');
        }
    })
}

2.使用

let ws;  //全局变量
//链接socket  根据场景调用
let params = {};//连接socket所需的参数 不需要设置全局 哪里用到就在哪里写
connectSocket(params).then(res=>{
            ws = res;
 })
//链接成功后 使用阶段  此处只是举例说明  具体使用可参照业务逻辑进行修改
if(ws.readyState == 1){ //1为链接成功
       request(`xxxxx`, {
          method: 'POST',
          headers: config.headers,
          body: config.parseJson(data),
          credentials: "include"
        }).then((res) => {
             if (res.data.code == 1) {
                   let sendMsg = 'xxxx';//需发送的参数
                   ws.send(sendMsg);
             }else{
                   console.log(res.data.msg);
              }
         })
}else if(ws.readyState == 3){
         //连接已关闭或者没有链接成功  再次连接socket
         //此处可封装 重复调用
         let params = {};//连接socket所需参数
         connectSocket(params).then(res=>{
               ws = res;
          })
  }

//记得不使用的时候关闭socket
if (ws) {
     ws.close();
}

你可能感兴趣的:(实时通信socket封装及使用)