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部分

<script>
	import date from "@/utils/date.js"
	import {
		message_delete,
		message_list
	} from "@/api/hr/message"
	import send from "./send.vue"
	import ReconnectingWebSocket from 'reconnecting-websocket'
		import wsMixinsMethods from '@/utils/wsMixinsMethods'; //--------------------------------------------------------------------websocket
	export default {
			mixins: [wsMixinsMethods], //--------------------------------------------------------------------websocket
		components: {
			send
		},
		props: {
			width: {
				type: String,
				default: "420px"
			}
		},
		data() {
			return {
				userId: JSON.parse(window.localStorage.getItem("userInfo")).id,
				activeName: "first",
				msgList: [],
				timer: null,
				messageData: {},
				total:0,
				search:{
					pageNo:1,
					pageSize:60
				},
				throttle:false,
				isRefresh:false,
				socket:null,
				indexSendObj:{id:null},
			};
		},
		created() {
			this.initWebSocket();//打开webSocket
		},
		methods: {
			
			
			
			
			/*************** 获取数据或提交操作 ***************/
			scrollEvent(e){
				let msgListH=this.msgList.length;
				var container = this.$el.querySelector(".msgMain");
				if(container.scrollTop<50&&!this.throttle){
						++this.search.pageNo;
					if(msgListH<this.total){
						this.getList();
					}
				}
			},//滚动加载
			sendReviewComments(str){
				this.$refs.send.submit(str);
			},//发送审核意见
			handDel(index, id) {
				message_delete({
					id: id
				}).then(res => {
					this.msgList.splice(index, 1)
				})
			},//删除信息
			init(data) {
				this.messageData = data;
				this.getList(true);
			},//初始化数据由父组件调用
			initWebSocket(){
				this.registerWS('/socket/'+this.userId)
			},//初始化--------------------------------------------------------------------websocket
			selfWebsocketonmessage(e){
				let msg=JSON.parse(e);
				if(msg.id&&msg.businessId==this.messageData.businessId&&msg.flowCode==this.messageData.flowCode){//接收消息并判断是不是当前流程下的消息如果是则添加进数组
					++this.total;
					this.msgList.push(msg);
					this.scrollToBottom();
				}
			},//接受websocket信息--------------------------------------------------------------------websocket
			sendMsg(obj,state,isPSstate) {//isPSstate评审意见
				let param=Object.assign(obj,{"method":"LeaveMessage"})//特别注意这里,针对不同的通信这里传递的参数不一样一定要改成对应
				this.websocketsend(param);//发送websocket信息--------------------------------------------------------------------websocket
				if(isPSstate){
					this.$parent.isPSstateClsoe();
				}//评审写完评论的时候需要发送一条评信息
				if(state){
					this.$parent.createCG(obj.businessId)//首次评论需要调用父组件保存草稿
				}
			},//评论区发送完数据之后并发送websocket信息
			getList(state) {
				let param = {
					businessId: this.messageData.businessId,
					flowId: this.messageData.flowId,
					pageNo: this.search.pageNo,
					pageSize: this.search.pageSize,
				}
				this.throttle=true;
				message_list(param).then(res => {
					this.throttle=false;
					this.isRefresh=true;
					let list=this._.reverse(res.data.list)
					this.msgList =this._.uniqBy([...list,...this.msgList],'id');
					this.total = res.data.pagination.total;
					if(state){
						this.scrollToBottom();
					}
				})
			},
			/*************** 工具类 ***************/
			contentFun(str){
				return str.replace(/<img .*?>/g,"");
			},//过滤图片
			checkCallfileType(photoAddress,type){
				let arr=[];
				if(photoAddress){
					 JSON.parse(photoAddress).map(el=>{
						 if(el.filetype==type){
							 arr.push(el.url)
						 }
					 })
				}
				return arr
			},//检测图片放在一个数组内
			formatDate(val, pattern) {
				return !val || val == "" ? "" : date.formatDate.format(new Date(val), pattern);
			}, //格式化日期
			scrollToBottom() {
				this.$nextTick(() => {
					var container = this.$el.querySelector(".msgMain");
					container.scrollTop = container.scrollHeight;
				})
			},//滚动条置低
		},
		beforeDestroy() {
			  this.websocketclose();//注销websocket  
		},
	};
</script>

猜你喜欢

转载自blog.csdn.net/wgb0409/article/details/126749905
今日推荐