Vue的长连接,同时使用sockjs-client 和 stompjs

4,856 阅读1分钟

一、安装

npm install sockjs-client --save
npm install stompjs --save

二、使用

import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

methods: {
	// 初始化参数
    initWebSocket(){
    	this.connection();
        let self = this;
        // 断开重连机制, 尝试发送信息, 捕获异常发生时重连
        this.timer = setInterval(() => {
        	try {
            	self.stompClient.send('test');
            } catch (error) {
            	console.info("断线了:" + error);
                self.connection();
            }
        }, 5000);
    },
    
    // 建立连接
    connection(){
    	let orderId = '2006876567565656565654';
        // 建立连接对象
        // 连接服务端提供的通信接口,连接以后才可以订阅广播信息和个人信息
        this.socket = new SockJS(`http://22.0.157.40:10020/business-h5/orders/ws`);
        
        // 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(this.socket);
        // 定义客户端的认证信息,按需求配置
        let headers = {};
        
        // 向服务器发起websocket连接
        this.stompClient.connect(headers, () => {
        	// 订阅服务端提供的某个topic
            this.stompClient.subscribe('/status', (response) => {
            	console.info(response.body);
            });
        }, (err) => {
        	// 连接发生错误时的处理函数
            console.info('失败');
        });
    },
    
    // 断开连接
    disconnect(){
    	if (this.stompClient != null) {
        	this.stompClient.disconnect();
            console.info("Disconnected");
        }
    }
},
beforeDestory(){
	// 页面离开时断开连接,清除定时器
    this.disconnect();
    clearInterval(this.timer);
}