Last active
January 22, 2025 05:49
-
-
Save thekbbohara/e6f94112204dc980a53bc1540975d41a to your computer and use it in GitHub Desktop.
service.socket.io.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Server, type Socket } from "socket.io"; | |
| class SocketService { | |
| private static instance: SocketService; | |
| private _io: Server; | |
| private _sockets: Record<string, Socket> = {}; // Store sockets by user ID | |
| private constructor() { | |
| console.log("Initializing Socket Service..."); | |
| this._io = new Server({ | |
| cors: { | |
| allowedHeaders: ["*"], | |
| origin: "*", | |
| }, | |
| }); | |
| } | |
| // Singleton pattern to ensure only one instance exists | |
| public static getInstance(): SocketService { | |
| if (!SocketService.instance) { | |
| SocketService.instance = new SocketService(); | |
| } | |
| return SocketService.instance; | |
| } | |
| // Initialize Socket.IO event listeners | |
| public initListener(): void { | |
| this._io.on("connect", (socket: Socket) => { | |
| console.log(`Socket connected: ${socket.id}`); | |
| // Handle disconnect event | |
| socket.on("disconnect", (disconnectReason: string) => { | |
| console.info("Disconnect reason:", disconnectReason); | |
| // Clean up disconnected sockets | |
| for (const [userId, userSocket] of Object.entries(this._sockets)) { | |
| if (userSocket.id === socket.id) { | |
| delete this._sockets[userId]; | |
| console.info(`User ${userId} disconnected`); | |
| break; | |
| } | |
| } | |
| }); | |
| }); | |
| } | |
| // Getter for the Socket.IO server instance | |
| public get io(): Server { | |
| return this._io; | |
| } | |
| // Emit an event to all connected clients | |
| public emit(event: string, data: string): void { | |
| // data : json.stringify | |
| this._io.emit(event, data); | |
| } | |
| } | |
| export default SocketService.getInstance(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment