# Class WebSocket

java.lang.Object
com.codename1.io.WebSocket

public final class WebSocket extends Object

Client-side WebSocket. Connections are created via `build(java.lang.String)` and configured with fluent handler setters before being started with `connect()`:

    WebSocket ws = WebSocket.build("wss://example.com/chat")
        .onConnect(w        -> w.send("hello"))
        .onTextMessage((w, m) -> Log.p("recv " + m))
        .onClose((w, c, r)  -> Log.p("closed " + c + " / " + r))
        .onError((w, e)     -> Log.e(e))
        .connect();

Each handler receives the `WebSocket` as its first argument so it can send, query state, or close without capturing an external reference.

Handlers fire on a background thread. Use `Display.getInstance().callSerially(...)` inside a handler if you need to touch UI from it.

Use `isSupported()` to check at runtime whether the current port supports WebSocket -- older ports return `false` and `build(java.lang.String)` will throw on them.

- ## Nested Class Summary

  Nested Classes
  Modifier and Type
  Class
  Description
  `static interface`
  `WebSocket.BinaryHandler`
  Handler for an incoming binary frame.
  `static interface`
  `WebSocket.CloseHandler`
  Handler for the close event.
  `static interface`
  `WebSocket.ConnectHandler`
  Handler for the connection-established event.
  `static interface`
  `WebSocket.ErrorHandler`
  Handler for transport- or protocol-level errors.
  `static interface`
  `WebSocket.TextHandler`
  Handler for an incoming text frame.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `static WebSocket`
  `build(String url)`
  Create an unconnected WebSocket bound to `url`.
  `void`
  `close()`
  Close the connection.
  `WebSocket`
  `connect()`
  Start the handshake using the platform default connect timeout.
  `WebSocket`
  `connect(int connectTimeoutMs)`
  Start the handshake with an explicit connect timeout in milliseconds.
  `WebSocketState`
  `getReadyState()`
  `String`
  `getSelectedSubprotocol()`
  The subprotocol the server selected during the handshake, or null when none was negotiated.
  `String`
  `getUrl()`
  `WebSocket`
  `header(String name, String value)`
  Add a header to the opening handshake.
  `static boolean`
  `isSupported()`
  Whether the current port supports WebSocket.
  `WebSocket`
  `onBinaryMessage(WebSocket.BinaryHandler handler)`
  Register a handler for incoming binary frames.
  `WebSocket`
  `onClose(WebSocket.CloseHandler handler)`
  Register a handler for the close event.
  `WebSocket`
  `onConnect(WebSocket.ConnectHandler handler)`
  Register a handler for the connection-established event.
  `WebSocket`
  `onError(WebSocket.ErrorHandler handler)`
  Register a handler for transport errors.
  `WebSocket`
  `onTextMessage(WebSocket.TextHandler handler)`
  Register a handler for incoming text frames.
  `void`
  `send(byte[] binary)`
  Send a binary frame.
  `void`
  `send(String text)`
  Send a text frame.
  `WebSocket`
  `subprotocols(String... protocols)`
  Offer one or more subprotocols (RFC 6455 `Sec-WebSocket-Protocol`), in preference order, to negotiate during the handshake.

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Method Details

  - ### isSupported

    public static boolean isSupported()
    Whether the current port supports WebSocket.

  - ### build

    public static WebSocket build(String url)
    Create an unconnected WebSocket bound to `url`. The URL must use the `ws://` or `wss://` scheme. Call `connect()` to start the handshake.
    Throws:
      `RuntimeException` - if the current port does not support WebSocket.

  - ### onConnect

    public WebSocket onConnect(WebSocket.ConnectHandler handler)
    Register a handler for the connection-established event. Returns `this` for chaining.

  - ### onTextMessage

    public WebSocket onTextMessage(WebSocket.TextHandler handler)
    Register a handler for incoming text frames. Returns `this` for chaining.

  - ### onBinaryMessage

    public WebSocket onBinaryMessage(WebSocket.BinaryHandler handler)
    Register a handler for incoming binary frames. Returns `this` for chaining.

  - ### onClose

    public WebSocket onClose(WebSocket.CloseHandler handler)
    Register a handler for the close event. Returns `this` for chaining.

  - ### onError

    public WebSocket onError(WebSocket.ErrorHandler handler)
    Register a handler for transport errors. Returns `this` for chaining.

  - ### subprotocols

    public WebSocket subprotocols(String... protocols)

    Offer one or more subprotocols (RFC 6455 `Sec-WebSocket-Protocol`), in preference order, to negotiate during the handshake. Must be called before `connect()`. After the connection opens, `getSelectedSubprotocol()` returns the one the server chose (or null). Returns `this` for chaining.

        WebSocket.build("wss://api.example.com/graphql")
            .subprotocols("graphql-transport-ws")
            .onConnect(w -> Log.p("using " + w.getSelectedSubprotocol()))
            .connect();

  - ### header

    public WebSocket header(String name, String value)

    Add a header to the opening handshake. Must be called before `connect()`. Passing a null value removes a previously set header. Returns `this` for chaining.

    Typically used to carry an authorization or attestation token, since a WebSocket has no other place to put one.

        WebSocket.build("wss://api.example.com/stream")
            .header("X-CN1-Attest", token)
            .connect();

    ###### Not supported everywhere

    Emitted on Android, desktop, Windows and Linux, which build the opening handshake themselves. Silently dropped on iOS and in the browser, which hand the handshake to a platform WebSocket that exposes no way to add headers to it.

    Where headers are unavailable, obtain a short-lived ticket over an ordinary HTTPS request -- which can be attested and pinned normally -- and pass it in the URL query instead. That also avoids leaking a long-lived credential into a URL.

    Headers the handshake sets itself -- `Host`, `Upgrade`, `Connection`, `Sec-WebSocket-Key`, `Sec-WebSocket-Version`, `Sec-WebSocket-Protocol` -- are reserved and are ignored if passed here. Use `subprotocols(java.lang.String...)` for the last of those.

  - ### getSelectedSubprotocol

    public String getSelectedSubprotocol()
    The subprotocol the server selected during the handshake, or null when none was negotiated. Valid once the `WebSocket.ConnectHandler` has fired.

  - ### connect

    public WebSocket connect()
    Start the handshake using the platform default connect timeout. Returns `this` for chaining; success is signalled asynchronously via the registered `WebSocket.ConnectHandler`.

  - ### connect

    public WebSocket connect(int connectTimeoutMs)
    Start the handshake with an explicit connect timeout in milliseconds. `0` means "use platform default".

  - ### close

    public void close()
    Close the connection. Idempotent.

  - ### send

    public void send(String text)
    Send a text frame. Throws `IllegalStateException` if the connection is not `WebSocketState.OPEN`.

  - ### send

    public void send(byte[] binary)
    Send a binary frame. Throws `IllegalStateException` if the connection is not `WebSocketState.OPEN`.

  - ### getReadyState

    public WebSocketState getReadyState()

  - ### getUrl

    public String getUrl()