import { streamList } from "./config";
window.streamList = streamList
export default class WebSocketClient {
  constructor(url) {
    this.url = url;
    this.socket = null;
    this.getSocketCount = 0;
  }

  // 连接WebSocket服务器
  connect(onopen, onmessage, onclose) {
    this.socket = new WebSocket(window.streamList[this.getSocketCount] + this.url);

    this.socket.onopen = onopen

    this.socket.onmessage = onmessage

    // this.socket.onclose = () => {
    // };
    this.socket.onerror = () => {
      this.getSocketCount += 1
      if (this.getSocketCount < window.streamList.length) {
        this.connect(onopen, onmessage, onclose);
      } else {
      }
    };
  }

  // 发送消息
  send(message) {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    } else {
      // console.log("WebSocket连接尚未打开");
    }
  }

  // 关闭连接
  close() {
    this.socket.close();
  }
}