public final class WebSocket

  1. Object
  2. WebSocket

Client-side WebSocket. Connections are created via build 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 will throw on them.

Nested types

interface WebSocket.ConnectHandlerHandler for the connection-established event.
interface WebSocket.TextHandlerHandler for an incoming text frame.
interface WebSocket.BinaryHandlerHandler for an incoming binary frame.
interface WebSocket.CloseHandlerHandler for the close event.
interface WebSocket.ErrorHandlerHandler for transport- or protocol-level errors.

Methods

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

Inherited methods

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 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 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 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()