SockJS和Stomp建立Websocket连接

通过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';

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值