不废话了,直接上干货。可直接食用
ts刚开始用,不合理的地方欢迎指导,虚心请教
import {
onUnmounted, ref } from 'vue'
import {
useSystemStore } from '@/store/modules/systemStore/systemStore'
interface QueryType {
url: string //url
options?: OptionsType //配置
params?: object //url参数
onmessage?: Function //回调函数
}
interface OptionsType {
maxReconnect?: number //最大重连次数, -1 标识无限重连
interval?: number //心跳间隔
timeout?: number // 响应超时时间
pingMessage?: string // 心跳请求信息
}
const defaultOptions = {
maxReconnect: 6,
interval: 30 * 1000,
timeout: 10 * 1000,
pingMessage: 'ping'
}
/**
* websocket封装
* @param {object} param0
* @returns serverMessage, sendMessage, destroySocket
*/
export default function useWebSocket({
url, options = {
}, params, onmessage }: QueryType) {
const OPTION = {
...defaultOptions, ...options }
let socket: WebSocket | null = null //websocket实例
let pingTimeoutObj: NodeJS.Timeout | null = null //延时发送心跳的定时器
let pongTimeoutObj:

本文介绍了如何在Vue应用中使用WebSocket进行通信,包括封装接口、设置连接选项、处理连接状态变化、心跳检测以及断开连接的逻辑。同时提及了与系统存储模块的集成和参数编码方法。
最低0.47元/天 解锁文章
5824





