Class WebSocket
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 ClassesModifier and TypeClassDescriptionstatic interfaceHandler for an incoming binary frame.static interfaceHandler for the close event.static interfaceHandler for the connection-established event.static interfaceHandler for transport- or protocol-level errors.static interfaceHandler for an incoming text frame. -
Method Summary
Modifier and TypeMethodDescriptionstatic WebSocketCreate an unconnected WebSocket bound tourl.voidclose()Close the connection.connect()Start the handshake using the platform default connect timeout.connect(int connectTimeoutMs) Start the handshake with an explicit connect timeout in milliseconds.The subprotocol the server selected during the handshake, or null when none was negotiated.getUrl()Add a header to the opening handshake.static booleanWhether the current port supports WebSocket.onBinaryMessage(WebSocket.BinaryHandler handler) Register a handler for incoming binary frames.onClose(WebSocket.CloseHandler handler) Register a handler for the close event.onConnect(WebSocket.ConnectHandler handler) Register a handler for the connection-established event.onError(WebSocket.ErrorHandler handler) Register a handler for transport errors.onTextMessage(WebSocket.TextHandler handler) Register a handler for incoming text frames.voidsend(byte[] binary) Send a binary frame.voidSend a text frame.subprotocols(String... protocols) Offer one or more subprotocols (RFC 6455Sec-WebSocket-Protocol), in preference order, to negotiate during the handshake.
-
Method Details
-
isSupported
public static boolean isSupported()Whether the current port supports WebSocket. -
build
Create an unconnected WebSocket bound tourl. The URL must use thews://orwss://scheme. Callconnect()to start the handshake.- Throws:
RuntimeException- if the current port does not support WebSocket.
-
onConnect
Register a handler for the connection-established event. Returnsthisfor chaining. -
onTextMessage
Register a handler for incoming text frames. Returnsthisfor chaining. -
onBinaryMessage
Register a handler for incoming binary frames. Returnsthisfor chaining. -
onClose
Register a handler for the close event. Returnsthisfor chaining. -
onError
Register a handler for transport errors. Returnsthisfor chaining. -
subprotocols
Offer one or more subprotocols (RFC 6455
Sec-WebSocket-Protocol), in preference order, to negotiate during the handshake. Must be called beforeconnect(). After the connection opens,getSelectedSubprotocol()returns the one the server chose (or null). Returnsthisfor chaining.WebSocket.build("wss://api.example.com/graphql") .subprotocols("graphql-transport-ws") .onConnect(w -> Log.p("using " + w.getSelectedSubprotocol())) .connect(); -
header
Add a header to the opening handshake. Must be called before
connect(). Passing a null value removes a previously set header. Returnsthisfor 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. Usesubprotocols(java.lang.String...)for the last of those. -
getSelectedSubprotocol
The subprotocol the server selected during the handshake, or null when none was negotiated. Valid once theWebSocket.ConnectHandlerhas fired. -
connect
Start the handshake using the platform default connect timeout. Returnsthisfor chaining; success is signalled asynchronously via the registeredWebSocket.ConnectHandler. -
connect
Start the handshake with an explicit connect timeout in milliseconds.0means "use platform default". -
close
public void close()Close the connection. Idempotent. -
send
Send a text frame. ThrowsIllegalStateExceptionif the connection is notWebSocketState.OPEN. -
send
public void send(byte[] binary) Send a binary frame. ThrowsIllegalStateExceptionif the connection is notWebSocketState.OPEN. -
getReadyState
-
getUrl
-