diff --git a/backend/src/index.js b/backend/src/index.js index 355e0673..055aa8d3 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -26,6 +26,6 @@ try { console.error('Failed to initialize WebSocket server:', error); } -app.listen(PORT, () => { +server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); diff --git a/backend/src/websocketServer.js b/backend/src/websocketServer.js index de324c78..e2f71fd7 100644 --- a/backend/src/websocketServer.js +++ b/backend/src/websocketServer.js @@ -1,9 +1,25 @@ import { WebSocketServer } from 'ws'; const activeConnections = {}; // token별로 연결을 관리하기 위한 객체 +const clientLocations = {}; export const initializeWebSocketServer = server => { - const wss = new WebSocketServer({ server }); + const wss = new WebSocketServer({ + server, + verifyClient: (info, done) => { + const { origin } = info; + + if (origin === 'http://localhost:5173') { + done(true); + } else { + done(false, 403, 'Forbidden: Origin not allowed'); + } + }, + }); + + wss.on('error', err => { + console.error('WebSocket Server Error:', err); + }); wss.on('connection', (ws, req) => { // URL에서 token 추출 @@ -26,9 +42,40 @@ export const initializeWebSocketServer = server => { console.log(`Client connected with token: ${token}`); + // 새 클라이언트에게 기존 클라이언트의 위치 전송 + ws.send( + JSON.stringify({ + type: 'init', + clients: Object.entries(clientLocations).map(([clientToken, location]) => ({ + token: clientToken, + location, + })), + }), + ); + // 클라이언트로부터 메시지 받았을 때의 이벤트 처리 ws.on('message', message => { - console.log(`Received from ${token}:`, message); + try { + const data = JSON.parse(message); + if (data.type === 'location' && data.location) { + clientLocations[token] = data.location; + + // 모든 클라이언트에게 위치 정보 전송 + Object.keys(activeConnections).forEach(otherToken => { + if (activeConnections[otherToken].readyState === ws.OPEN) { + activeConnections[otherToken].send( + JSON.stringify({ + type: 'location', + token, + location: data.location, + }), + ); + } + }); + } + } catch (err) { + console.error('Invalid message format:', err); + } }); // 클라이언트 연결 종료 시 @@ -36,6 +83,7 @@ export const initializeWebSocketServer = server => { console.log(`Client disconnected with token: ${token}, Code: ${code}, Reason: ${reason}`); // 연결이 종료되면 activeConnections에서 해당 token 제거 delete activeConnections[token]; + delete clientLocations[token]; }); }); }; diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index a7e44f41..345dbd45 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -5,4 +5,7 @@ import tsconfigPaths from 'vite-tsconfig-paths'; // 추가된 부분 // https://vite.dev/config/ export default defineConfig({ plugins: [react(), tsconfigPaths()], // tsconfigPaths 플러그인 추가 + server: { + hmr: false, // HMR 완전히 비활성화 + }, });