websocket在vue中使用

导入插件

import Rwebsocket from 'reconnecting-websocket';

 新建一个WebSocket.js文件

import Rwebsocket from 'reconnecting-websocket';
/**
 * 实例化WS
 */
function initQDWS(wsUrl) {
  const ws = new Rwebsocket(wsUrl, null, { debug: false, reconnectInterval: 3000 });
  //console.info(`ws地址:${wsUrl}`);
  return ws;
}
/**
 * 打开监听
 * @param ws
 * @param fun
 * @returns {null}
 */
function listnerOpen(ws, fun) {
  if (ws == undefined) {
    return null;
  } else if (typeof fun === 'function') {
    // 打开回调方法
    ws.onopen = function (event) {
      fun(event.data);
    };
  }
}

/**
 * 错误监听
 * @param ws
 * @param fun
 * @returns {null}
 */
function listnerError(ws, fun) {
  if (ws == undefined) {
    return null;
  } else if (typeof fun === 'function') {
    // 错误回调方法
    ws.onerror = function (event) {
      fun(event.data);
    };
  }
}
/**
 * 监听消息
 * @param ws
 * @param fun
 * @returns {null}
 */
function listnerMessage(ws, fun) {
  if (ws == undefined) {
    return null;
  } else if (typeof fun === 'function') {
    // 接收到消息的回调方法
    ws.onmessage = function (event) {
      fun(event.data);
    };
  }
}

/**
 * 关闭监听
 * @param ws
 * @param fun
 * @returns {null}
 */
function listnerClose(ws, fun) {
  if (ws == undefined) {
    return null;
  } else {
    // 关闭回调方法
    if (typeof fun === 'function') {
      ws.onclose = function () {
        fun();
      };
    }
    return null;
  }
}

/**
 * 注册监听
 * @param ws
 * @param callBacks
 * @returns {null}
 */
function registerListner(ws, callBacks) {
  if (ws == null) {
    return null;
  } else {
    const open = callBacks.open || null;
    const error = callBacks.error || null;
    const message = callBacks.message || null;
    const close = callBacks.close || null;
    listnerOpen(ws, open);
    listnerError(ws, error);
    listnerMessage(ws, message);
    listnerClose(ws, close);
  }
}
export default {
  initQDWS,
  registerListner,
};

 新建一个wsMixinsMethods.js文件

import WebSocket from './WebSocket';
const mixins = {
  // 定义data数据
  data() {
    return {
      refreshDataWS: null,
    };
  },
  methods: {
    // 注册ws
    registerWS(wsUrl) {
      const vm = this;
    
      vm.refreshDataWS = WebSocket.initQDWS("ws://192.168.1.141:48080"+wsUrl);
      WebSocket.registerListner(vm.refreshDataWS,
        {
          open: vm.websocketonopen,
          error: vm.websocketonerror,
          message: vm.websocketonmessage,
          close: vm.websocketclose,
        });
      return vm.refreshDataWS;
    },
    websocketonopen() {
   //   console.info('连接成功');
    },
    // 连接建立失败重连
    websocketonerror() {
    //  console.info('连接失败');
    },
    // 数据接收后执行的操作
    websocketonmessage(e) {
		if(e){
			if (this.selfWebsocketonmessage && typeof this.selfWebsocketonmessage === "function") return this.selfWebsocketonmessage(e)
			 try {
			   const info = JSON.parse(e);
			  /* console.info(`消息推送===`);
			   console.info(`${e}`); */
			//   eventBus.$emit('wsRefreshAssemblyData', info);//更改数据
			 } catch (event) {
			 /*  console.info(`消息推送========`);
			   console.info(`${event}`); */
			 }
		}
		
    },
    // 发送消息
    websocketsend(Data) { // 数据发送
     // console.info(`数据发送========${Data}`);
      this.refreshDataWS.send(JSON.stringify(Data));
    },
    // 关闭连接
    websocketclose(e) { // 关闭
    //  console.log('断开连接', e);
    },
  },
};
export default mixins;

在vue页面中使用 

注意无关代码可以不用看只关注------websocket部分

你可能感兴趣的:(vue小功能封装,websocket,vue.js,网络协议)