File size: 1,693 Bytes
40e991e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { io, Socket } from 'socket.io-client';

const SOCKET_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000';

class SocketService {
  private socket: Socket | null = null;

  connect(token: string): Socket {
    if (this.socket?.connected) {
      return this.socket;
    }

    this.socket = io(SOCKET_URL, {
      autoConnect: false,
    });

    this.socket.connect();

    // 连接成功后发送认证信息
    this.socket.on('connect', () => {
      console.log('Socket连接成功');
      this.socket?.emit('join', { token });
    });

    this.socket.on('disconnect', () => {
      console.log('Socket连接断开');
    });

    this.socket.on('error', (error) => {
      console.error('Socket错误:', error);
    });

    return this.socket;
  }

  disconnect(): void {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
  }

  getSocket(): Socket | null {
    return this.socket;
  }

  sendMessage(content: string, room: string = 'general'): void {
    if (this.socket?.connected) {
      this.socket.emit('sendMessage', { content, room });
    }
  }

  onNewMessage(callback: (message: any) => void): void {
    this.socket?.on('newMessage', callback);
  }

  onUserJoined(callback: (user: any) => void): void {
    this.socket?.on('userJoined', callback);
  }

  onUserLeft(callback: (user: any) => void): void {
    this.socket?.on('userLeft', callback);
  }

  onOnlineUsers(callback: (users: any[]) => void): void {
    this.socket?.on('onlineUsers', callback);
  }

  offAllListeners(): void {
    this.socket?.removeAllListeners();
  }
}

export const socketService = new SocketService();
export default socketService;