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();
}

本文介绍如何利用SockJS和STOMP.js实现WebSocket连接,包括安装依赖、配置客户端认证信息、建立及断开连接等步骤,并提供封装后的组件使用案例。
3935

被折叠的 条评论
为什么被折叠?



