TooTallNate/Java-WebSocket · error · IllegalStateException

socket has already been set

Error message

socket has already been set

What it means

This is a defensive state guard in the deprecated WebSocketClient.setSocket method: it fires when the client's internal socket field has already been assigned and setSocket is called a second time. The WebSocket library allows configuring the underlying socket only once, before connect(); re-invoking setSocket would silently replace an existing socket and corrupt connection state, so the IllegalStateException aborts the configuration. The faulty input is a second setSocket call on the same client instance (typically by application code that retries configuration or mixes deprecated setSocket with new-style setup).

Solutions

  1. Call setSocket at most once per WebSocketClient instance, before connect()
  2. Remove duplicate initialization code paths that both configure the socket (e.g. both setSocket and setSocketFactory usage/retry)
  3. Create a new WebSocketClient instance instead of re-configuring an existing one
  4. Migrate to setSocketFactory, which is the non-deprecated replacement and does not carry this one-shot restriction
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at src/main/java/org/java_websocket/client/WebSocketClient.java:905 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of TooTallNate/Java-WebSocket@afeacbf8c0 (2026-09-09). Data as JSON: /api/errors/18791d3be80b1bbb. Report an issue: GitHub.

Appendix: source

Thrown at src/main/java/org/java_websocket/client/WebSocketClient.java:905

   */
  public void setProxy(Proxy proxy) {
    if (proxy == null) {
      throw new IllegalArgumentException();
    }
    this.proxy = proxy;
  }

  /**
   * Accepts bound and unbound sockets.<br> This method must be called before <code>connect</code>.
   * If the given socket is not yet bound it will be bound to the uri specified in the constructor.
   *
   * @param socket The socket which should be used for the connection
   * @deprecated use setSocketFactory
   */
  @Deprecated
  public void setSocket(Socket socket) {
    if (this.socket != null) {
      throw new IllegalStateException("socket has already been set");
    }
    this.socket = socket;
  }

  /**
   * Accepts a SocketFactory.<br> This method must be called before <code>connect</code>. The socket
   * will be bound to the uri specified in the constructor.
   *
   * @param socketFactory The socket factory which should be used for the connection.
   */
  public void setSocketFactory(SocketFactory socketFactory) {
    this.socketFactory = socketFactory;
  }

  @Override
  public void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin) {
    engine.sendFragmentedFrame(op, buffer, fin);
  }

View on GitHub (pinned to afeacbf8c0)