Skip to content

Commit

Permalink
clean up working again websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
Bit-Barron committed Nov 2, 2024
1 parent 127ae5d commit c6feb82
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 54 deletions.
9 changes: 8 additions & 1 deletion src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,21 @@ import type { Handle } from '@sveltejs/kit';
import { locale } from 'svelte-i18n';
import { lucia } from '$lib/server/auth';
import { initSocketIO } from '@/server/socket';
import { createServer } from 'http';

const httpServer = createServer();
initSocketIO(httpServer);

httpServer.listen(3001, () => {
console.log('Socket.IO server listening on port 3001');
});

let isSocketInitialized = false;

export const handle: Handle = async ({ event, resolve }) => {
if (!isSocketInitialized && event.platform?.server) {
isSocketInitialized = true;
initSocketIO(event.platform.server);
console.log('Socket.IO server initialized');
}

const lang =
Expand Down
87 changes: 36 additions & 51 deletions src/lib/server/socket.ts
Original file line number Diff line number Diff line change
@@ -1,65 +1,50 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Server } from 'socket.io';
import type { Server as HTTPServer } from 'http';
import { dev } from '$app/environment';

let io: Server | null = null;

export const initSocketIO = (httpServer: HTTPServer) => {
if (!io) {
console.log('Initializing Socket.IO server...');
io = new Server(httpServer, {
path: '/socket.io',
cors: {
origin: ['https://youtubepedia.barron.agency', 'http://localhost:3000'],
methods: ['GET', 'POST'],
credentials: true
},
transports: ['websocket', 'polling']
});

io.on('connection', (socket) => {
console.log('Client connected', socket.id);

const userId = socket.handshake.auth.userId;
if (userId) {
socket.join(userId);
console.log(`User ${userId} joined their room`);
let initializationPromise: Promise<Server> | null = null;

export const initSocketIO = (httpServer: HTTPServer): Promise<Server> => {
if (!initializationPromise) {
initializationPromise = new Promise((resolve) => {
if (!io) {
console.log('Initializing Socket.IO server...');
io = new Server(httpServer, {
path: '/socket.io',
cors: {
origin: dev ? ['http://localhost:3000'] : ['https://youtubepedia.barron.agency'],
methods: ['GET', 'POST'],
credentials: true
},
transports: ['websocket', 'polling']
});

io.on('connection', (socket) => {
console.log('Client connected', socket.id);

const userId = socket.handshake.auth.userId;
if (userId) {
socket.join(userId);
console.log(`User ${userId} joined their room`);
}

socket.on('disconnect', () => {
console.log('Client disconnected', socket.id);
});
});

console.log('Socket.IO server initialized successfully');
}

socket.on('disconnect', () => {
console.log('Client disconnected', socket.id);
});
resolve(io);
});

console.log('Socket.IO server initialized successfully');
}
return io;
return initializationPromise;
};

export const getIO = (): Server => {
if (!io) {
console.warn('Socket.IO accessed before initialization, waiting...');
return new Proxy({} as Server, {
get: (target, prop) => {
if (prop === 'to' || prop === 'emit') {
return (...args: any[]) => {
setTimeout(() => {
const realIO = getIO();
if (realIO && prop in realIO) {
(realIO[prop as keyof Server] as any)(...args);
}
}, 100);
};
}
return () => {
console.warn('Socket.IO method called before initialization');
};
}
});
throw new Error('Socket.IO has not been initialized');
}
return io;
};

export const isSocketInitialized = (): boolean => {
return io !== null;
};
3 changes: 2 additions & 1 deletion src/routes/(main)/dashboard/chat/[id]/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,9 @@ export const actions = {
});

const io = getIO();
io.to(userId).emit('new-question', questionChat);
const working = io.to(userId).emit('new-question', questionChat);

console.log(working);
const response = await fetch('/api/ask', {
method: 'POST',
headers: {
Expand Down
2 changes: 1 addition & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const webSocketServer = {

const io = new Server(server.httpServer, {
cors: {
origin: 'http://localhost:3000',
origin: '*',
methods: ['GET', 'POST'],
credentials: true
}
Expand Down

0 comments on commit c6feb82

Please sign in to comment.