|
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; |
|
|