class WebSocketClient {
constructor(url) {
this.url = url;
this.websocket = null;
this.onopen = null;
this.onmessage = null;
this.onclose = null;
this.onerror = null;
}
connect () {
this.websocket = new WebSocket(this.url);
this.websocket.onopen = (event) => {
if (this.onopen) this.onopen(event);
};
this.websocket.onmessage = (event) => {
if (this.onmessage) this.onmessage(event);
};
this.websocket.onclose = (event) => {
if (this.onclose) this.onclose(event);
};
this.websocket.onerror = (event) => {
if (this.onerror) this.onerror(event);
};
}
send (data) {
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
this.websocket.send(data);
}
}
close () {
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
this.websocket.close();
}
}
}
let wsClient = new WebSocketClient('ws://localhost:8080');
wsClient.onopen = () => {
console.log('连接成功');
};
wsClient.onmessage = (event) => {
console.log('接收到服务器发送的消息:', event.data);
};
wsClient.onclose = function () {
console.log('连接断开,正在尝试重新连接...');
setTimeout(() => {
wsClient = new WebSocket('ws://localhost:8080');
}, 5000);
};
wsClient.connect();