import { WEBSOCKET_BASE_URL } from '@/config/setting'
|
|
export default class WebSocketClient {
|
|
constructor(path) {
|
this.url = WEBSOCKET_BASE_URL + path;
|
this.webSocket = null;
|
}
|
|
connect() {
|
if (!this.url) {
|
console.error('WebSocketClient: Cannot connect without url.');
|
return;
|
}
|
|
this.webSocket = new WebSocket(this.url);
|
|
this.webSocket.onopen = (event) => {
|
console.log('WebSocket connection opened:');
|
// 连接成功后可以发送消息
|
// this.sendMessage('Hello Server!');
|
};
|
|
this.webSocket.onmessage = (event) => {
|
console.log('WebSocket message received:', event.data);
|
this.onMessage(event.data);
|
};
|
|
this.webSocket.onerror = (event) => {
|
console.error('WebSocket error observed:', event);
|
};
|
|
this.webSocket.onclose = (event) => {
|
console.log('WebSocket connection closed!');
|
this.reconnect();
|
};
|
}
|
|
sendMessage(message) {
|
if (this.webSocket.readyState === WebSocket.OPEN) {
|
this.webSocket.send(message);
|
} else {
|
console.error('WebSocketClient: Cannot send message, WebSocket connection is not open.');
|
}
|
}
|
|
onMessage(data) {
|
// 子类可能会重写这个方法来处理消息
|
console.log('WebSocketClient: Message received:', data);
|
}
|
|
close() {
|
if (this.webSocket.readyState === WebSocket.OPEN) {
|
this.webSocket.close();
|
}
|
}
|
|
reconnect() {
|
setTimeout(() => {
|
console.log('WebSocketClient: Attempting to reconnect...');
|
this.connect();
|
}, 3000);
|
}
|
|
}
|