Vue中使用SockJS实现webSocket通信
目录
文章目录隐藏
SockJS 简介
SockJS 是一个浏览器 JavaScript 库,它提供了一个类似于网络的对象。SockJS 提供了一个连贯的、跨浏览器的 Javascript API,它在浏览器和 web 服务器之间创建了一个低延迟、全双工、跨域通信通道。
- SockJS 会优先采用 websocket,如果在不支持 websocket 的浏览器中,会自动降为轮询的方式;
- 兼容跨浏览器,支持跨域;
SockJS 在 vue 中的使用
锁屏情况下,js 会停止工作,这时,ws 会自动关闭,当屏幕唤醒时,通过触发 onclose 事件,ws
又会进行重连。在某些特殊业务场景下,需要注意下这种情况。
安装 sockjs-client 和 stompjs
npm install sockjs-client npm install stompjs
页面中引入 SockJS 和 Stomp
import SockJS from 'sockjs-client'; import Stomp from 'stompjs';
实现思路
export default { data() { return { stompClient: '', timer: '', socket: null, userId: '', } }, mounted() { this.init(); }, beforeDestroy: function() { // 页面离开时断开连接,清除定时器 this.disconnect() clearInterval(this.timer) }, methods: { init() { this.connection() let _this = this // 断开重连机制 this.timer = setInterval(() = >{ try { _this.stompClient.send('test') } catch(e) { console.log('连接中断:' + e) _this.connection() } }, 10000) }, connection() { this.socket = new SockJS(config.webSocketUrl + '/web-socket/ws') //协议字段 this.stompClient = Stomp.over(this.socket) let __this = this // 向服务器发起 websocket 连接 let token = userUtils.getToken() this.stompClient.connect({ userId: this.userId, // 携带客户端信息 token: token }, function connectCallback() { __this.stompClient.subscribe('/user/exchange/stompUser/stompUserNotice', //订阅地址 (response) = >{ console.log('连接成功', response) //接收 response 数据 }) }, function errorCallBack(error) { console.log('连接失败:' + error) }) }, disconnect() { clearInterval(this.timer) if (this.stompClient) { this.stompClient.disconnect() } }, } }
即时通信
心跳检测
ws 建立成功时便进行心跳请求(每隔一段时间发送一个 PING),同时初始化 超时重连。如果在达到心跳规定次数后仍没有返回 PONG,则判定心跳超时,前端主动关闭 ws,触发 ws 重连。
【注意】:ws 重连的时候,要清空之前的心跳定时器。
什么时候关闭心跳连接
- 心跳超时(连接层不断)的情况,则前端可主动关闭 ws;
- 连接未建立成功(如 TCP 连接断掉),ws 自动关闭;
- 服务端关闭(如多端剔除),这是要防止前端进行重连。
websocket 相关文章推荐:
原文链接:点击这里
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Vue中使用SockJS实现webSocket通信
码云笔记 » Vue中使用SockJS实现webSocket通信