class封装websocket

该文描述了一个WebSocket服务的实现,包括从配置文件中获取URL,处理连接的打开、关闭、错误事件,以及自动重连机制。它定义了两个WebSocket服务子类,ws1和ws2,分别用于不同的服务端点,实现了发送消息和处理返回的方法。此外,还使用了ElementUI的Loading组件进行加载状态显示。
摘要由CSDN通过智能技术生成
1、index.js的内容
import {wsConfig} from "./config";
import { Loading } from 'element-ui'
let loadingInstance = null;

class wsObj{
​    constructor(fn) {
​        this.socket = null;
​        this.typeName = null;
​        this.url = null;
​        window.WebSocket = window.WebSocket || window.MozWebSocket;
​        if (!window.WebSocket) return console.error('错误: 浏览器不支持websocket');
​        this.messageList = new Map;
​        this.onopen = (() => {
​            console.log(`open ${this.typeName} websocket`);
​            if(fn) fn();
​        })
​        this.onmessage = (e => {
​            //处理各种推送消息
​            this.handleEvent(e.data)
​        })
​        this.onerror = (e => {
​            console.warn(`${this.typeName}websocket服务已断开,正在重连`);
​            console.error("error " + e);
​            this.reConnect(this);
​            stopWebsocket();
​        })
​        this.onclose = (() => {
​            console.warn("close websocket");
​            console.warn(`${this.typeName}websocket服务已断开,正在重连`);
​            this.reConnect(this)
​            stopWebsocket();
​        })
​        this.initWs();
​    }

​    initWs() {
​        console.warn(`初始化${this.typeName}websocket连接`);
​        this.socket = new WebSocket(this.url); // 创建连接并注册响应函数
​        this.socket.onopen = () => {
​            this.onopen();
​        };
​        this.socket.onclose = () => {
​            this.onclose();
​            this.socket = null; // 清理
​            stopWebsocket();
​        };
​        this.socket.onerror = (e) => {
​            this.onerror(e);
​            stopWebsocket();
​        }
​        this.socket.onmessage = (e) => {
​            this.onmessage(e);
​        };
​    }

​    reConnect(that) {
​      if (that.isReconnect) return;
​      that.isReconnect = true;
​      //没连接上会一直重连,设置延迟避免请求过多
​      setTimeout(() => {
​        that.initWs();
​        that.isReconnect = false;
​      }, 2000);
​    }
}

//websocket服务1
export class ws1 extends wsObj{
  constructor() {
​    this.typeName = wsConfig.wsDevice.des;
​    this.url = wsConfig.wsDevice.path;
  }

  sends(device, method, params, callback) {
​    let loginParam = {
​      method,
​      device,
​      params,
​      id: new Date()
​    };
​    let action = loginParam.device + loginParam.method;
​    if (this.messageList.has(action)) {
​        this.messageList.delete(action);
​    }
​    this.messageList.set(action, callback);
​    //组装json数据
​    console.log(`send入参:${JSON.stringify(loginParam)}`);
​    this.socket.send(JSON.stringify(loginParam))
  }

  handleEvent(message) {
​    message = JSON.parse(message);
​    let action = message.device + message.method; //只取返回中的接口名
​    this.messageList.get(action)(message); //通过接口名调用存储的回调函数,通过回调将message抛出
  }
}


//websocket服务2
export class ws2 extends wsObj{
  constructor() {
​    this.typeName = wsConfig.wsCHR.des;
​    this.url = wsConfig.wsCHR.path;
  }
  sends(params, callback) {
​    let loginParam = wsConfig.wsCHR.loginParam;
​    loginParam = Object.assign(loginParam, {
​      input: JSON.stringify(params.input)
​    })
​    let action = wsConfig.wsCHR.des;
​    if (this.messageList.has(action)) {
​      this.messageList.delete(action);
​    }
​    this.messageList.set(action, callback);
​    //组装json数据
​    loginParam = `NationEcTrans^${action}|${JSON.stringify(loginParam)}`;
​    console.log(`send医保入参:${params.title}:${loginParam}`);
​    loadingInstance = Loading.service({
​      background: 'rgba(0, 0, 0, 0.7)',
​      lock: true,
​      text: '请稍候...'
​    })
​    this.socket.send(loginParam)
  }
  
  handleEvent (message) {
​    console.log(`msg返回:${message}`);
​    let action = wsConfig.wsCHR.des;
​    loadingInstance.close();
​    this.messageList.get(action)(message); //通过接口名调用存储的回调函数,通过回调将message抛出
  }
}
2、config.js的内容
//websocket服务配置项
export default {
  ws1: {
​    path: 'ws://localhost:7000/ws',
​    des: 'ws1',
  },
  ws2: {
​    path: 'ws://127.0.0.1:9000',
​    des: 'ws2',
​    loginParam: {
​      infno: null,                        
​      dev_no: null,          
​      infver: 'V1.0',                      
​      opter_type: '1',                        
​      opter: '1',                     
​      opter_name: '1',                  
​      enc_type: "1",
​    }
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值