Skip to content

Commit

Permalink
Merge pull request #203 from boostcampwm-2024/feature/be/#40-connectS…
Browse files Browse the repository at this point in the history
…ocket

[BE][Feat] #40 : websocket 연결
  • Loading branch information
happyhyep authored Nov 19, 2024
2 parents 7520a2f + 1e159bb commit 30349ec
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
2 changes: 1 addition & 1 deletion backend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
});
33 changes: 29 additions & 4 deletions backend/src/websocketServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,20 @@ import { WebSocketServer } from 'ws';
const activeConnections = {}; // token별로 연결을 관리하기 위한 객체

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 추출
Expand All @@ -27,12 +40,24 @@ export const initializeWebSocketServer = server => {
console.log(`Client connected with token: ${token}`);

// 클라이언트로부터 메시지 받았을 때의 이벤트 처리
ws.on('message', message => {
console.log(`Received from ${token}:`, message);
wss.on('message', message => {
try {
const data = JSON.parse(message); // 위치 데이터 수신
if (data.latitude && data.longitude) {
// 브로드캐스트: 모든 클라이언트에게 위치 정보 전달
Object.values(activeConnections).forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ token, ...data }));
}
});
}
} catch (err) {
console.error('Invalid message received:', err);
}
});

// 클라이언트 연결 종료 시
ws.on('close', (code, reason) => {
wss.on('close', (code, reason) => {
console.log(`Client disconnected with token: ${token}, Code: ${code}, Reason: ${reason}`);
// 연결이 종료되면 activeConnections에서 해당 token 제거
delete activeConnections[token];
Expand Down
3 changes: 3 additions & 0 deletions frontend/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 완전히 비활성화
},
});

0 comments on commit 30349ec

Please sign in to comment.