Vue+websocket+stompjs实现长连接(用于实时接收消息)

本文档展示了如何在Vue项目中使用Stompjs库来实现WebSocket长连接,通过`yarn add stompjs`安装依赖,然后在组件的`mounted`阶段建立连接。在`onConnected`回调中订阅指定的消息交换,当收到消息时更新通知计数。此外,还包含了断开连接的方法以及在组件销毁时解除监听的逻辑。
摘要由CSDN通过智能技术生成

参考

1、安装

yarn add stompjs

2、引入

import Stomp from "stompjs";

3、使用

<template>
	<!--通过点击消息图标来触发事件-->
	<img src="message.png" alt="" @click="openMessage" />
</template>

<script>
	import Stomp from "stompjs";

	export default {
		data() {
			return {
				client: undefined
			}
		},
		mounted() {
			this.connect() //页面挂载触发长连接
		},
		methods: {
			openMessage() {
				NoticeCount().then(res => {
					if (res.success) {
						this.num = res.data;
					}
				});
			},
			connect() {
				//VUE_APP_URL="wss://abcd.net/ws";   //后端提供
				const url = process.env.VUE_APP_URL;
				this.client = Stomp.client(url);
				const headers = {
					login: "admin",
					passcode: "admin",
					host: "/",
					"heart-beat": "0,0"
				};
				//client.connect(login, passcode, connectCallback, errorCallback, host);
				this.client.connect(headers, this.onConnected, this.onFailed);
			},
			onConnected() {
				const id = window.localStorage.id;
				const exchange = `/long/connection/${id}`;//后端提供
				//目的地(destination),回调函数(callback);还有一个可选的参数headers
				//client.subscribe(destination, successCallback, errorCallback);
				this.client.subscribe(exchange, this.responseCallback, this.onFailed);//订阅消息
			},
			onFailed() {
				setTimeout(() => {
					this.connect();
				}, 5000);
			},
			responseCallback() {
				NoticeCount().then(res => {
					if (res.success) {
						this.num = res.data;
					}
				});
			},
			disconnect() {
				if (this.client != null) {
					this.client.disconnect();
				}
			},
		},
		destroyed() {
			// 销毁监听
			this.disconnect();
		}
	}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值