54 lines
1.7 KiB
JavaScript
54 lines
1.7 KiB
JavaScript
|
|
// WebSocket communication module
|
||
|
|
export class WebSocketManager {
|
||
|
|
constructor(onMessage, onStatusChange) {
|
||
|
|
this.websocket = null;
|
||
|
|
this.onMessage = onMessage;
|
||
|
|
this.onStatusChange = onStatusChange;
|
||
|
|
}
|
||
|
|
|
||
|
|
async connect() {
|
||
|
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||
|
|
const wsUrl = `${protocol}//${window.location.host}/ws`;
|
||
|
|
|
||
|
|
try {
|
||
|
|
this.websocket = new WebSocket(wsUrl);
|
||
|
|
|
||
|
|
this.websocket.onopen = () => {
|
||
|
|
this.onStatusChange('connected');
|
||
|
|
};
|
||
|
|
|
||
|
|
this.websocket.onclose = () => {
|
||
|
|
this.onStatusChange('disconnected');
|
||
|
|
// Reconnect after 5 seconds
|
||
|
|
setTimeout(() => this.connect(), 5000);
|
||
|
|
};
|
||
|
|
|
||
|
|
this.websocket.onerror = (error) => {
|
||
|
|
console.error('WebSocket error:', error);
|
||
|
|
this.onStatusChange('disconnected');
|
||
|
|
};
|
||
|
|
|
||
|
|
this.websocket.onmessage = (event) => {
|
||
|
|
try {
|
||
|
|
const message = JSON.parse(event.data);
|
||
|
|
|
||
|
|
|
||
|
|
this.onMessage(message);
|
||
|
|
} catch (error) {
|
||
|
|
console.error('Failed to parse WebSocket message:', error);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
} catch (error) {
|
||
|
|
console.error('WebSocket connection failed:', error);
|
||
|
|
this.onStatusChange('disconnected');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
disconnect() {
|
||
|
|
if (this.websocket) {
|
||
|
|
this.websocket.close();
|
||
|
|
this.websocket = null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|