|
|
@@ -0,0 +1,65 @@
|
|
|
+class SocketClient<T> {
|
|
|
+ private socket: WebSocket | null = null;
|
|
|
+ private retryCount: number = 0;
|
|
|
+ private readonly maxRetries: number = -1;
|
|
|
+
|
|
|
+ constructor(private listener: (data: T) => void, private url: string, private protocol?: string) {
|
|
|
+ this.connect();
|
|
|
+ }
|
|
|
+ private isConnected(): boolean {
|
|
|
+ return this.socket !== null && this.socket.readyState === WebSocket.OPEN;
|
|
|
+ }
|
|
|
+ private connect() {
|
|
|
+ this.socket = new WebSocket(this.url, this.protocol);
|
|
|
+
|
|
|
+ this.socket.addEventListener('open', (event: Event) => {
|
|
|
+ console.log('WebSocket连接成功:', event);
|
|
|
+ this.retryCount = 0;
|
|
|
+ });
|
|
|
+ this.socket.addEventListener('message', (event: MessageEvent) => {
|
|
|
+ try {
|
|
|
+ this.listener?.(JSON.parse(event.data) as T);
|
|
|
+ } catch (error) {
|
|
|
+ this.listener?.(event.data as T);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ this.socket.addEventListener('close', (event: CloseEvent) => {
|
|
|
+ console.error('WebSocket连接关闭:', event);
|
|
|
+ });
|
|
|
+ this.socket.addEventListener('error', (event: Event) => {
|
|
|
+ console.error('WebSocket连接异常:', event);
|
|
|
+ this.connectAfresh();
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ public connectAfresh(isRestart: boolean = false) {
|
|
|
+ if (!isRestart) {
|
|
|
+ this.retryCount = 0;
|
|
|
+ }
|
|
|
+ if (!this.isConnected() && (this.maxRetries === -1 || this.retryCount < this.maxRetries)) {
|
|
|
+ console.log(`尝试连接中... (${this.retryCount + 1}/${this.maxRetries})`);
|
|
|
+ setTimeout(() => this.connect(), this.getRetryInterval());
|
|
|
+ this.retryCount++;
|
|
|
+ } else if (!this.isConnected()) {
|
|
|
+ console.log('已经达到最大尝试次数,依然无法连接');
|
|
|
+ }
|
|
|
+ }
|
|
|
+ private getRetryInterval(): number {
|
|
|
+ // 为了提高效率,每次重连间隔递增
|
|
|
+ return 1000 * Math.pow(2, 100);
|
|
|
+ }
|
|
|
+ public send(message: string): boolean {
|
|
|
+ if (this.isConnected()) {
|
|
|
+ this.socket?.send(message);
|
|
|
+ return true;
|
|
|
+ } else {
|
|
|
+ console.error('WebSocket未连接,无法发送消息.');
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ public close() {
|
|
|
+ this.socket?.close();
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+export default SocketClient;
|