通过SockJS和Stomp建立
1. 安装
npm install sockjs-client --save
npm install stompjs --save
2. 使用
// import SockJS from "sockjs-client"; 这样引入控制台报错:找不到global...
import SockJS from "sockjs-client/dist/sockjs.min.js";
import Stomp from "stompjs";
import { baseUrl } from '@/utils';
import { getCacheToken } from '@/utils';
let stompClient: Stomp.Client;
const token = getCacheToken();
const ws_url = `${baseUrl}/message/ws?token=${token}`;
// 初始化连接
export const initWebSocket = () => {
const socket = new SockJS(ws_url, '', {
timeout: 10000
});
stompClient = Stomp.over(socket);
stompClient.connect(
{},
() => {
// 成功的回调
},
() => {
// 失败的回调
}
);
};
// 断开连接
export const destroyConnect = () => {
stompClient && stompClient.disconnect(() => {
console.log('ws连接断开!')
});
}
// 订阅消息
export const subscribeMessage = (topic, callback) => {
if (!stompClient || !topic) retrun;
const subscribeInstance = stompClient.subscribe(topic, (res) => {
callback(JSON.parse(res));
},
{ id: topic } //id可以不传,如果传id可以使用id取消订阅消息
)
return subscribeInstance; // 可以调用subscribeInstance.unsubscribe()取消订阅
}
// 1. 通过ID取消订阅消息
export const unSubscribeMessage = (topic) => {
if (!stompClient || !topic) retrun;
stompClient.unsubscribe(topic);
}
// 2. 通过subscribeMessage返回的实例取消订阅消息
const subscribeInstance = subscribeMessage(*****)
subscribeInstance.unsubscribe()
3. 单独使用Stomp建立连接
SockJS的主要作用是提供一种WebScoket的兼容性解决方案,使得不支持WebSocket的浏览器也可以使用WebSocket。如果确定浏览器支持可以不使用。
// 使用过程和上面基本一致
// 初始化连接
export const initWebSocket = () => {
stompClient = Stomp.client(ws_url)
stompClient.connect(
{},
() => {
// 成功的回调
},
() => {
// 失败的回调
}
);
};
4. 注意
如果是TS的项目可能会报:无法找到模块“sockjs-client/dist/sockjs.min.js”的声明文件。“c:/STMF/dev-3/smart-monitor-engine-web/node_modules/sockjs-client/dist/sockjs.min.js”隐式拥有 "any" 类型。
尝试使用 npm i --save-dev @types/sockjs-client
(如果存在),或者添加一个包含 declare module 'sockjs-client/dist/sockjs.min.js';
的新声明(.d.ts)文件ts(7016)
新建一个vite-env.d.ts
文件,在文件中加入
/// <reference types="vite/client" />
declare module 'sockjs-client/dist/sockjs.min.js';