WebSocketClient.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. class SocketClient<T> {
  2. private socket: WebSocket | null = null;
  3. private retryCount: number = 0;
  4. private readonly maxRetries: number = -1;
  5. constructor(private listener: (data: T) => void, private url: string, private protocol?: string) {
  6. this.connect();
  7. }
  8. private isConnected(): boolean {
  9. return this.socket !== null && this.socket.readyState === WebSocket.OPEN;
  10. }
  11. private connect() {
  12. this.socket = new WebSocket(this.url, this.protocol);
  13. this.socket.addEventListener('open', (event: Event) => {
  14. console.log('WebSocket连接成功:', event);
  15. this.retryCount = 0;
  16. });
  17. this.socket.addEventListener('message', (event: MessageEvent) => {
  18. try {
  19. this.listener?.(JSON.parse(event.data) as T);
  20. } catch (error) {
  21. this.listener?.(event.data as T);
  22. }
  23. });
  24. this.socket.addEventListener('close', (event: CloseEvent) => {
  25. console.error('WebSocket连接关闭:', event);
  26. });
  27. this.socket.addEventListener('error', (event: Event) => {
  28. console.error('WebSocket连接异常:', event);
  29. this.connectAfresh();
  30. });
  31. }
  32. public connectAfresh(isRestart: boolean = false) {
  33. if (!isRestart) {
  34. this.retryCount = 0;
  35. }
  36. if (!this.isConnected() && (this.maxRetries === -1 || this.retryCount < this.maxRetries)) {
  37. console.log(`尝试连接中... (${this.retryCount + 1}/${this.maxRetries})`);
  38. setTimeout(() => this.connect(), this.getRetryInterval());
  39. this.retryCount++;
  40. } else if (!this.isConnected()) {
  41. console.log('已经达到最大尝试次数,依然无法连接');
  42. }
  43. }
  44. private getRetryInterval(): number {
  45. // 为了提高效率,每次重连间隔递增
  46. return 1000 * Math.pow(2, 100);
  47. }
  48. public send(message: string): boolean {
  49. if (this.isConnected()) {
  50. this.socket?.send(message);
  51. return true;
  52. } else {
  53. console.error('WebSocket未连接,无法发送消息.');
  54. return false;
  55. }
  56. }
  57. public close() {
  58. this.socket?.close();
  59. }
  60. }
  61. export default SocketClient;