Skip to content

Commit

Permalink
Feat: WebSocket 로직 수정 및 채팅 관련 기능 추가 (#26)
Browse files Browse the repository at this point in the history
- WebSocket 연결 안정성을 위한 재연결 로직 추가
- 채팅 메시지 송수신을 위한 메서드 구현
- WebSocket 연결 상태 관리
- 실시간 메시지 처리를 위한 핸들러 지원
  • Loading branch information
sunglitter committed Dec 1, 2024
1 parent 2e93a26 commit c060597
Showing 1 changed file with 80 additions and 26 deletions.
106 changes: 80 additions & 26 deletions src/utils/webSocket.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,80 @@
export const connectWebSocket = (
path: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onMessage: (data: any) => void
): WebSocket => {
const ws = new WebSocket(`wss://your-backend-domain.com${path}`);

ws.onopen = () => {
console.log('WebSocket connection established');
};

ws.onmessage = (event) => {
const data = JSON.parse(event.data);
onMessage(data); // 메시지 처리
};

ws.onclose = (event) => {
console.log('WebSocket connection closed:', event);
};

ws.onerror = (error) => {
console.error('WebSocket error occurred:', error);
};

return ws;
};
/* eslint-disable @typescript-eslint/no-explicit-any */
export class WebSocketService {
private socket: WebSocket | null = null;
private reconnectAttempts = 0;
private maxReconnectAttempts = 5;

constructor(private url: string) {}

connect(
onMessage: (data: any) => void,
onOpen?: () => void,
onClose?: () => void,
onError?: (error: any) => void
) {
this.socket = new WebSocket(this.url);

this.socket.onopen = () => {
console.log('WebSocket connected');
if (onOpen) onOpen();
this.reconnectAttempts = 0; // 성공적으로 연결되면 재시도 횟수 초기화
};

this.socket.onmessage = (event) => {
const data = JSON.parse(event.data);
if (onMessage) onMessage(data);
};

this.socket.onclose = () => {
console.log('WebSocket disconnected');
if (onClose) onClose();
this.reconnect();
};

this.socket.onerror = (error) => {
console.error('WebSocket error:', error);
if (onError) onError(error);
};
}

send(destination: string, message: any) {
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
console.warn('WebSocket is not connected');
return;
}

const payload = JSON.stringify({ destination, message });
console.log(`Sending message to ${destination}:`, payload);
this.socket.send(payload);
}

close() {
if (this.socket) {
this.socket.close();
console.log('WebSocket connection closed');
}
}

private reconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
console.log(
`Reconnecting... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`
);
setTimeout(() => {
this.connect(
() => {},
() => {},
() => {},
() => {}
);
}, 3000); // 3초 후 재연결 시도
} else {
console.error('Max reconnect attempts reached');
}
}
}

export const webSocketService = new WebSocketService(
'ws://your-api-endpoint.com/websocket'
);

0 comments on commit c060597

Please sign in to comment.