Files
pqs-9100_client/frontend/src/utils/webSocketClient.ts

697 lines
21 KiB
TypeScript
Raw Normal View History

2025-08-06 13:33:09 +08:00
/**
* WebSocket客户端服务
* WebSocket连接管理
* JWT token解析
*
* @author hongawen
* @version 2.0
*/
import { ElMessage } from "element-plus";
import { jwtUtil } from "./jwtUtil";
// ============================================================================
// 类型定义 (Types & Interfaces)
// ============================================================================
/**
* WebSocket消息接口定义WebSocketVO结构
*/
interface WebSocketMessage<T = any> {
type: string; // 消息类型
requestId?: string; // 请求ID
operateCode?: string; // 操作代码
code?: number; // 状态码
desc?: string; // 描述信息
data?: T; // 泛型数据
}
/**
*
*/
type CallbackFunction<T = any> = (message: WebSocketMessage<T>) => void;
/**
* WebSocket配置接口
*/
interface SocketConfig {
url: string; // WebSocket服务器地址
heartbeatInterval?: number; // 心跳间隔时间(ms)
reconnectDelay?: number; // 重连延迟时间(ms)
maxReconnectAttempts?: number; // 最大重连次数
timeout?: number; // 超时时间(ms)
}
2024-12-20 16:32:03 +08:00
2025-08-06 13:33:09 +08:00
/**
*
*/
enum ConnectionStatus {
DISCONNECTED = 'disconnected', // 未连接
CONNECTING = 'connecting', // 连接中
CONNECTED = 'connected', // 已连接
RECONNECTING = 'reconnecting', // 重连中
ERROR = 'error' // 连接错误
}
/**
* WebSocket消息类型定义命名空间
*/
namespace WebSocketMessageTypes {
/**
*
*/
export interface PreTestMessage {
deviceId?: string;
status?: string;
progress?: number;
errorInfo?: string;
}
/**
*
*/
export interface CoefficientMessage {
deviceId: string;
channel: number;
voltage?: string;
current?: string;
calibrationResult?: boolean;
}
/**
*
*/
export interface TestMessage {
deviceId: string;
testType: string;
testResult?: 'success' | 'failed' | 'processing';
testData?: any;
}
/**
*
*/
export interface CommonResponse {
success: boolean;
message?: string;
timestamp?: number;
}
}
2025-08-06 13:33:09 +08:00
// ============================================================================
// 导出类型
// ============================================================================
export type {
WebSocketMessage,
CallbackFunction,
SocketConfig,
WebSocketMessageTypes
};
export {
ConnectionStatus
};
// ============================================================================
// 主要服务类
// ============================================================================
/**
* WebSocket服务类
* WebSocket连接管理功能
*/
2024-12-20 16:32:03 +08:00
export default class SocketService {
2025-08-06 13:33:09 +08:00
// ========================================================================
// 静态属性和方法 (Static)
// ========================================================================
/**
*
*/
private static instance: SocketService | null = null;
/**
*
* @returns SocketService实例
*/
static get Instance(): SocketService {
2024-12-20 16:32:03 +08:00
if (!this.instance) {
this.instance = new SocketService();
}
return this.instance;
}
2025-08-06 13:33:09 +08:00
// ========================================================================
// 实例属性 (Properties)
// ========================================================================
/**
* WebSocket连接实例
*/
private ws: WebSocket | null = null;
/**
*
*/
private callBackMapping: Record<string, CallbackFunction<any>> = {};
/**
*
*/
private connectionStatus: ConnectionStatus = ConnectionStatus.DISCONNECTED;
/**
*
*/
private sendRetryCount: number = 0;
/**
*
*/
private connectRetryCount: number = 0;
/**
* Worker实例
*/
private heartbeatWorker: Worker | null = null;
/**
* Worker脚本的Blob URL
*/
private workerBlobUrl: string | null = null;
/**
*
*/
private lastResponseHeartTime: number = Date.now();
/**
* WebSocket连接配置
*/
private config: SocketConfig = {
2025-08-20 20:02:22 +08:00
// url: 'ws://127.0.0.1:7777/hello',
url: 'ws://192.168.1.124:7777/hello',
2025-08-06 13:33:09 +08:00
heartbeatInterval: 9000, // 9秒心跳间隔
reconnectDelay: 5000, // 5秒重连延迟
maxReconnectAttempts: 5, // 最多重连5次
timeout: 30000 // 30秒超时
};
// ========================================================================
// 构造函数 (Constructor)
// ========================================================================
/**
*
*/
private constructor() {
this.initializeProperties();
}
/**
*
*/
private initializeProperties(): void {
this.lastResponseHeartTime = Date.now();
}
// ========================================================================
// Getter属性 (Computed)
// ========================================================================
/**
*
* @returns
*/
get connected(): boolean {
return this.connectionStatus === ConnectionStatus.CONNECTED;
}
// ========================================================================
// 公共方法 (Public Methods)
// ========================================================================
/**
* WebSocket连接参数
* @param config
*/
public configure(config: Partial<SocketConfig>): void {
this.config = { ...this.config, ...config };
}
/**
* WebSocket服务器
*/
public connect(): Promise<void> | void {
// 检查浏览器支持
2024-12-20 16:32:03 +08:00
if (!window.WebSocket) {
2025-08-06 13:33:09 +08:00
console.log('您的浏览器不支持WebSocket');
return;
}
// 防止重复连接
if (this.connectionStatus === ConnectionStatus.CONNECTING || this.connected) {
console.warn('WebSocket已连接或正在连接中');
return;
}
this.connectionStatus = ConnectionStatus.CONNECTING;
try {
this.ws = new WebSocket(this.buildWebSocketUrl());
this.setupEventHandlersLegacy();
} catch (error) {
this.connectionStatus = ConnectionStatus.ERROR;
console.error('WebSocket连接失败:', error);
}
}
/**
* WebSocket服务器
* @returns Promise<void>
*/
public connectAsync(): Promise<void> {
return new Promise((resolve, reject) => {
// 检查浏览器支持
if (!window.WebSocket) {
const error = '您的浏览器不支持WebSocket';
console.error(error);
reject(new Error(error));
return;
}
// 防止重复连接
if (this.connectionStatus === ConnectionStatus.CONNECTING || this.connected) {
console.warn('WebSocket已连接或正在连接中');
resolve();
return;
}
this.connectionStatus = ConnectionStatus.CONNECTING;
try {
this.ws = new WebSocket(this.buildWebSocketUrl());
this.setupEventHandlers(resolve, reject);
} catch (error) {
this.connectionStatus = ConnectionStatus.ERROR;
reject(error);
}
});
}
/**
*
* @param messageType
* @param callback
*/
public registerCallBack<T = any>(messageType: string, callback: CallbackFunction<T>): void {
if (!messageType || typeof callback !== 'function') {
console.error('注册回调函数参数无效');
return;
}
this.callBackMapping[messageType] = callback;
console.log(`注册消息处理器: ${messageType}`);
}
/**
*
* @param messageType
*/
public unRegisterCallBack(messageType: string): void {
if (this.callBackMapping[messageType]) {
delete this.callBackMapping[messageType];
console.log(`注销消息处理器: ${messageType}`);
2024-12-20 16:32:03 +08:00
}
2025-08-06 13:33:09 +08:00
}
/**
* WebSocket服务器
* @param data
* @returns Promise<void>
*/
public send(data: any): Promise<void> {
return new Promise((resolve, reject) => {
if (!this.connected || !this.ws) {
// 未连接时的重试机制
if (this.sendRetryCount < 3) {
this.sendRetryCount++;
setTimeout(() => {
this.send(data).then(resolve).catch(reject);
}, this.sendRetryCount * 500);
return;
} else {
reject(new Error('WebSocket未连接且重试失败'));
return;
}
}
try {
// 重置重试计数
this.sendRetryCount = 0;
// 尝试发送JSON数据失败则发送原始数据
const message = typeof data === 'string' ? data : JSON.stringify(data);
this.ws.send(message);
console.log('发送消息:', message);
resolve();
} catch (error) {
console.error('发送消息失败:', error);
reject(error);
}
});
}
/**
* WebSocket连接
*/
public closeWs(): void {
console.log('正在关闭WebSocket连接...');
// 清理心跳
this.clearHeartbeat();
// 关闭连接
if (this.ws) {
this.ws.close(1000, '主动关闭连接');
this.ws = null;
}
// 更新状态
this.connectionStatus = ConnectionStatus.DISCONNECTED;
this.connectRetryCount = 0;
this.sendRetryCount = 0;
console.log('WebSocket连接已关闭');
}
/**
*
* @returns
*/
public getConnectionStatus(): ConnectionStatus {
return this.connectionStatus;
}
2025-01-17 09:14:19 +08:00
2025-08-06 13:33:09 +08:00
/**
*
* @returns
*/
public getConnectionStats(): {
status: ConnectionStatus;
connectRetryCount: number;
lastResponseHeartTime: number;
} {
return {
status: this.connectionStatus,
connectRetryCount: this.connectRetryCount,
lastResponseHeartTime: this.lastResponseHeartTime
};
}
2024-12-20 16:32:03 +08:00
2025-08-06 13:33:09 +08:00
// ========================================================================
// 私有方法 (Private Methods)
// ========================================================================
/**
* WebSocket URL
* JWT token中获取loginName作为name参数
* @returns WebSocket URL
*/
private buildWebSocketUrl(): string {
const { url } = this.config;
// 直接从JWT token中获取loginName作为name参数
const loginName = jwtUtil.getLoginName();
if (loginName) {
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}name=${encodeURIComponent(loginName)}`;
2024-12-20 16:32:03 +08:00
}
2025-08-06 13:33:09 +08:00
// 如果无法获取loginName返回原始URL并输出警告
console.warn('无法从JWT token中获取loginNameWebSocket连接可能会失败');
return url;
}
/**
* WebSocket事件处理器
* @param resolve Promise resolve回调
* @param reject Promise reject回调
*/
private setupEventHandlers(resolve: () => void, reject: (error: Error) => void): void {
if (!this.ws) return;
// 连接成功事件
this.ws.onopen = () => {
ElMessage.success("WebSocket连接服务端成功");
console.log('WebSocket连接成功');
this.connectionStatus = ConnectionStatus.CONNECTED;
this.connectRetryCount = 0;
this.startHeartbeat();
resolve();
};
// 连接关闭事件
this.ws.onclose = (event: CloseEvent) => {
console.log('WebSocket连接关闭', event.code, event.reason);
this.connectionStatus = ConnectionStatus.DISCONNECTED;
this.clearHeartbeat();
// 非正常关闭且未超过最大重连次数,尝试重连
if (event.code !== 1000 && this.connectRetryCount < this.config.maxReconnectAttempts!) {
this.attemptReconnect();
}
};
2025-01-17 09:14:19 +08:00
2025-08-06 13:33:09 +08:00
// 连接错误事件
this.ws.onerror = (error: Event) => {
console.error('WebSocket连接错误:', error);
ElMessage.error("WebSocket连接异常");
this.connectionStatus = ConnectionStatus.ERROR;
reject(new Error('WebSocket连接失败'));
};
2024-12-20 16:32:03 +08:00
2025-08-06 13:33:09 +08:00
// 消息接收事件
this.ws.onmessage = (event: MessageEvent) => {
this.handleMessage(event);
};
}
2024-12-20 16:32:03 +08:00
2025-08-06 13:33:09 +08:00
/**
* WebSocket事件处理器
*/
private setupEventHandlersLegacy(): void {
if (!this.ws) return;
// 连接成功事件
2024-12-20 16:32:03 +08:00
this.ws.onopen = () => {
ElMessage.success("webSocket连接服务端成功了");
console.log('连接服务端成功了');
2025-08-06 13:33:09 +08:00
this.connectionStatus = ConnectionStatus.CONNECTED;
2024-12-20 16:32:03 +08:00
this.connectRetryCount = 0;
2025-01-16 15:57:29 +08:00
this.startHeartbeat();
2024-12-20 16:32:03 +08:00
};
2025-08-06 13:33:09 +08:00
// 连接关闭事件
this.ws.onclose = (event: CloseEvent) => {
2025-02-19 11:00:09 +08:00
console.log('连接webSocket服务端关闭');
2025-08-06 13:33:09 +08:00
this.connectionStatus = ConnectionStatus.DISCONNECTED;
2025-01-16 15:57:29 +08:00
this.clearHeartbeat();
2025-08-06 13:33:09 +08:00
// 保持原有的重连逻辑(被注释掉的)
// this.connectRetryCount++;
/* setTimeout(() => {
2025-02-18 14:59:13 +08:00
this.connect();
}, 500 * this.connectRetryCount);*/
2024-12-20 16:32:03 +08:00
};
2025-01-17 09:14:19 +08:00
2025-08-06 13:33:09 +08:00
// 连接错误事件
2025-01-17 09:14:19 +08:00
this.ws.onerror = () => {
ElMessage.error("webSocket连接异常");
2025-08-06 13:33:09 +08:00
this.connectionStatus = ConnectionStatus.ERROR;
};
2025-01-17 09:14:19 +08:00
2025-08-06 13:33:09 +08:00
// 消息接收事件
this.ws.onmessage = (event: MessageEvent) => {
this.handleMessage(event);
2025-01-17 09:14:19 +08:00
};
2025-08-06 13:33:09 +08:00
}
2025-01-17 09:14:19 +08:00
2025-08-06 13:33:09 +08:00
/**
*
* JSON消息和普通文本消息
* @param event WebSocket消息事件
*/
private handleMessage(event: MessageEvent): void {
// console.log('Received message:', event.data);
// 心跳响应处理
if (event.data === 'over') {
console.log(`${new Date().toLocaleTimeString()} - 收到心跳响应`);
this.lastResponseHeartTime = Date.now();
return;
}
2025-02-18 14:59:13 +08:00
2025-08-06 13:33:09 +08:00
// 检查消息是否为空或无效
if (!event.data || event.data.trim() === '') {
console.warn('收到空消息,跳过处理');
return;
}
2025-02-18 14:59:13 +08:00
2025-08-06 13:33:09 +08:00
// 业务消息处理
try {
// 检查是否为JSON格式
if (typeof event.data === 'string' && (event.data.startsWith('{') || event.data.startsWith('['))) {
const message: WebSocketMessage = JSON.parse(event.data);
2025-02-18 14:59:13 +08:00
if (message?.type && this.callBackMapping[message.type]) {
this.callBackMapping[message.type](message);
} else {
2025-08-06 13:33:09 +08:00
console.warn('未找到对应的消息处理器:', message.type);
}
} else {
// 非JSON格式的消息作为普通文本处理
console.log('收到非JSON格式消息:', event.data);
// 可以添加文本消息的处理逻辑
if (this.callBackMapping['text']) {
this.callBackMapping['text']({
type: 'text',
data: event.data
});
2025-02-18 14:59:13 +08:00
}
2024-12-20 16:32:03 +08:00
}
2025-08-06 13:33:09 +08:00
} catch (error) {
console.error('消息解析失败:', event.data, error);
console.error('消息类型:', typeof event.data);
console.error('消息长度:', event.data?.length || 0);
}
2024-12-20 16:32:03 +08:00
}
2025-01-16 15:57:29 +08:00
2025-08-06 13:33:09 +08:00
// ========================================================================
// 重连机制相关方法
// ========================================================================
2025-01-16 15:57:29 +08:00
2025-08-06 13:33:09 +08:00
/**
* WebSocket
*/
private attemptReconnect(): void {
if (this.connectionStatus === ConnectionStatus.RECONNECTING) {
return;
}
2025-01-16 15:57:29 +08:00
2025-08-06 13:33:09 +08:00
this.connectionStatus = ConnectionStatus.RECONNECTING;
this.connectRetryCount++;
const delay = this.config.reconnectDelay! * this.connectRetryCount;
console.log(`尝试第${this.connectRetryCount}次重连,${delay}ms后开始...`);
setTimeout(() => {
try {
const result = this.connect();
if (result instanceof Promise) {
result.catch((error: any) => {
console.error('重连失败:', error);
});
}
} catch (error: any) {
console.error('重连失败:', error);
2025-01-16 15:57:29 +08:00
}
2025-08-06 13:33:09 +08:00
}, delay);
2025-01-16 15:57:29 +08:00
}
2025-08-06 13:33:09 +08:00
// ========================================================================
// 心跳机制相关方法
// ========================================================================
2025-01-16 15:57:29 +08:00
2025-08-06 13:33:09 +08:00
/**
*
*/
private startHeartbeat(): void {
this.lastResponseHeartTime = Date.now();
this.createHeartbeatWorker();
2025-01-16 15:57:29 +08:00
}
2025-08-06 13:33:09 +08:00
/**
* Worker
* 使Worker在独立线程中处理心跳定时器线
*/
private createHeartbeatWorker(): void {
try {
// 创建Worker脚本
const workerScript = `
setInterval(function() {
postMessage('heartbeat');
}, ${this.config.heartbeatInterval});
`;
this.workerBlobUrl = window.URL.createObjectURL(
new Blob([workerScript], { type: 'application/javascript' })
);
this.heartbeatWorker = new Worker(this.workerBlobUrl);
// 心跳Worker消息处理
this.heartbeatWorker.onmessage = (event: MessageEvent) => {
this.handleHeartbeatTick();
};
// Worker错误处理
this.heartbeatWorker.onerror = (error: ErrorEvent) => {
console.error('心跳Worker错误:', error);
this.clearHeartbeat();
};
} catch (error) {
console.error('创建心跳Worker失败:', error);
2025-01-16 15:57:29 +08:00
}
}
2025-08-06 13:33:09 +08:00
/**
*
*
*/
private handleHeartbeatTick(): void {
// 检查是否超时(距离上次收到心跳响应的时间)
const timeSinceLastResponse = Date.now() - this.lastResponseHeartTime;
if (timeSinceLastResponse > this.config.timeout!) {
console.error(`WebSocket心跳超时: ${timeSinceLastResponse}ms > ${this.config.timeout}ms`);
ElMessage.error("WebSocket连接超时请检查网络连接");
this.clearHeartbeat();
this.closeWs();
return;
}
this.sendHeartbeat();
2024-12-20 16:32:03 +08:00
}
2025-08-06 13:33:09 +08:00
/**
*
*/
private sendHeartbeat(): void {
if (this.connected && this.ws) {
console.log(`${new Date().toLocaleTimeString()} - 发送心跳消息`);
this.ws.send('alive');
2024-12-20 16:32:03 +08:00
}
}
2025-08-06 13:33:09 +08:00
/**
*
* Worker并清理相关资源
*/
private clearHeartbeat(): void {
if (this.heartbeatWorker) {
this.heartbeatWorker.terminate();
this.heartbeatWorker = null;
}
if (this.workerBlobUrl) {
window.URL.revokeObjectURL(this.workerBlobUrl);
this.workerBlobUrl = null;
2024-12-20 16:32:03 +08:00
}
}
2025-08-06 13:33:09 +08:00
}