File size: 993 Bytes
a6b6c66 | 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 | import { Server as SocketServer } from 'socket.io';
import { Server as HttpServer } from 'http';
let io: SocketServer | null = null;
export function initSocket(server: any) {
io = new SocketServer(server, {
cors: {
origin: "*", // Adjust in production
methods: ["GET", "POST"]
},
transports: ['websocket', 'polling']
});
io.on('connection', (socket) => {
console.log(`[Socket] Client connected: ${socket.id}`);
socket.on('subscribe', (userId: string) => {
console.log(`[Socket] User ${userId} subscribed to updates`);
socket.join(`user:${userId}`);
});
socket.on('disconnect', () => {
console.log(`[Socket] Client disconnected: ${socket.id}`);
});
});
return io;
}
export function getIO() {
if (!io) {
console.warn("[Socket] IO not initialized!");
}
return io;
}
export function emitToUser(userId: string, event: string, data: any) {
if (io) {
io.to(`user:${userId}`).emit(event, data);
}
}
|