WebSocketReconnect
工具类:
class WebSocketReconnect {
private url: string;
private socket: WebSocket | null = null;
private reconnectCount = 0;
private reconnectTimeout: NodeJS.Timeout | null = null;
private startTime: number | null = null;
private listerEvent: Map<string, Function[]> = new Map();
private manuallyClosed = false;
constructor(
url: string,
private maxReconnectAttempts = 3,
private reconnectInterval = 20000,
private maxReconnectTime = 180000
) {
if (!this.isValidWebSocketUrl(url)) {
throw new Error("Invalid WebSocket URL. Please check the URL format.");
}
this.url = url;
this.connect();
}
/**
* 检查 WebSocket URL 是否有效
* @param url WebSocket URL
* @returns 是否有效
*/
private isValidWebSocketUrl(url: string = this.url): boolean {
return /^wss?:\/\/.+/i.test(url);
}
/**
* 建立 WebSocket 连接
*/
private connect(): void {
console.log("Connecting to WebSocket...");
this.manuallyClosed = false; // 重置手动关闭标志位
this.socket = new WebSocket(this.url);
// 绑定事件
this.socket.onopen = () => {
console.log("WebSocket Connection Opened!");
this.triggerEvent("open");
this.clearReconnectTimeout();
this.reconnectCount = 0;
};
this.socket.onmessage = (event: MessageEvent) => {
console.log("WebSocket Message Received:", event.data);
this.triggerEvent("message", event.data);
};
this.socket.onclose = (event: CloseEvent) => {
console.log("WebSocket Connection Closed:", event);
this.triggerEvent("close", event);
if (!this.manuallyClosed) {
this.handleReconnect();
}
};
this.socket.onerror = (error: Event) => {
console.error("WebSocket Error Occurred:", error);
this.triggerEvent("error", error);
if (!this.manuallyClosed) {
this.handleReconnect();
}
};
}
/**
* 处理断线重连逻辑
*/
private handleReconnect(): void {
if (
this.reconnectCount < this.maxReconnectAttempts &&
(this.startTime === null || Date.now() - this.startTime < this.maxReconnectTime)
) {
this.reconnectCount++;
console.log(
`Attempting to reconnect (${this.reconnectCount}/${this.maxReconnectAttempts})...`
);
if (!this.startTime) {
this.startTime = Date.now();
}
this.reconnectTimeout = setTimeout(() => {
this.connect();
}, this.reconnectInterval);
} else {
console.log("Max reconnect attempts or time exceeded. Giving up.");
this.reconnectCount = 0;
this.startTime = null;
}
}
/**
* 清除重连定时器
*/
private clearReconnectTimeout(): void {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = null;
}
}
/**
* 触发注册的事件
* @param type 事件类型
* @param args 事件参数
*/
private triggerEvent(type: string, ...args: any[]): void {
const callbacks = this.listerEvent.get(type) || [];
callbacks.forEach((callback) => callback(...args));
}
/**
* 添加事件监听器
* @param type 事件类型
* @param callback 回调函数
*/
public on(type: string, callback: Function): void {
if (!this.listerEvent.has(type)) {
this.listerEvent.set(type, []);
}
this.listerEvent.get(type)!.push(callback);
}
/**
* 发送消息
* @param message 要发送的消息
*/
public send(message: string | ArrayBuffer | Blob): void {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(message);
} else {
console.error("WebSocket is not open. Unable to send message.");
}
}
/**
* 手动关闭 WebSocket 连接
*/
public close(): void {
this.manuallyClosed = true;
this.clearReconnectTimeout();
if (this.socket) {
this.socket.close();
}
this.reconnectCount = 0;
this.startTime = null;
}
/**
* 查询 WebSocket 当前状态
* @returns WebSocket 状态
*/
public getState(): string {
if (!this.socket) {
return "DISCONNECTED";
}
switch (this.socket.readyState) {
case WebSocket.CONNECTING:
return "CONNECTING";
case WebSocket.OPEN:
return "OPEN";
case WebSocket.CLOSING:
return "CLOSING";
case WebSocket.CLOSED:
return "CLOSED";
default:
return "UNKNOWN";
}
}
/**
* 动态更新 WebSocket URL 并重新连接
* @param newUrl 新的 WebSocket URL
*/
public updateUrl(newUrl: string): void {
if (!this.isValidWebSocketUrl(newUrl)) {
throw new Error("Invalid WebSocket URL.");
}
this.close();
this.url = newUrl;
this.connect();
}
}
export default WebSocketReconnect;
使用示例:
const ws = new WebSocketReconnect("wss://example.com", 5, 5000, 300000);
ws.on("open", () => console.log("WebSocket connected!"));
ws.on("message", (msg) => console.log("Received message:", msg));
ws.on("close", () => console.log("WebSocket closed."));
ws.on("error", (err) => console.error("WebSocket error:", err));
ws.send("Hello, server!");