vue使用sockjs实现websocket

1.引入

npm install sockjs-client

npm install stompj

注意:在引入后启动项目报错net 模块找不到时,需要进入module的stompjs中

cd node_modules

cd stompjs

执行

npm install net

2.组件中使用

import SockJS from  'sockjs-client';
import  Stomp from 'stompjs';
methods: {
  if(this.stompClient===""){
    this.connection();
  }
}
beforeDestroy() {
if(this.stompClient){
    this.disconnect();
}
},
methods: {
connection() {
    // 建立连接对象
    let socket = new SockJS('后台服务地址');
    // 获取STOMP子协议的客户端对象
    this.stompClient = Stomp.over(socket);
    this.stompClient.heartbeat.outgoing=20000;//前端对后台连接心跳监控间隔
    this.stompClient.heartbeat.incoming=0;//后台对前端心跳监控,若为0则不进行心跳监控
    // 定义客户端的认证信息,按需求配置
    let headers = {
        Authorization:用户身份验证信息
    }
    // 向服务器发起websocket连接
    this.stompClient.connect(headers,() => {
        this.stompClient.subscribe('订阅服务名称', (msg) => { // 订阅服务端提供的某个topic
            console.log('成功')
            console.log(msg);  // msg.body存放的是服务端发送给我们的信息
        },headers);
    }, (err)=>{
        console.log('失败')
        let errres=JSON.stringify(err);
      /*  if(errres.indexOf('Lost connection')>-1){
            this.connection();
        }*/重连判断
    });
},    //连接 后台
disconnect() {
    if (this.stompClient) {
        this.stompClient.disconnect();
    }
},  // 断开连接
}2.封装使用

封装成js引用

import SockJS from  'sockjs-client';
import  Stomp from 'stompjs';
export const initFirst=()=>{
    // 建立连接对象
    let stompClient="";
    let socket = new SockJS('https://m-nurse.xiaohudaojia.com//websocket/stomp');
    // 获取STOMP子协议的客户端对象
    stompClient = Stomp.over(socket);
    stompClient.heartbeat.outgoing=20000;
    stompClient.heartbeat.incoming=0;
    return stompClient;
}
export const connection=(mystompClient,callback)=>{
        // 定义客户端的认证信息,按需求配置
        let headers = {
            Authorization:用户身份验证信息
        }
        // 向服务器发起websocket连接
        mystompClient.connect(headers,() => {
            mystompClient.subscribe('订阅名称', (msg) => { // 订阅服务端提供的某个topic
                callback(msg);
            },headers);
        }, (err)=>{
            let errdata={
                type:"err",
                model:"",
                msg:err };
            callback(errdata);
        });
};
export const disconnect=(mystompClient)=>{
    if(mystompClient) {
        mystompClient.disconnect();
    }
}

组件中使用:

import {initFirst,connection,disconnect} from "js地址";

methods: {
if(this.stompClient===""){

this.stompClient=initFirst();

connection(this.stompClient,callback函数);
}
}
beforeDestroy() {
if(this.stompClient){
this.disconnect();
}

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值