WebSocket lifecycle
What you will learn
A WebSocket keeps a bidirectional message channel open after an HTTP upgrade. The Java client builds it asynchronously and receives events through a Listener. Input and output have separate lifecycles; demand controls receive callbacks, not a count of complete application messages. Bound assembled messages and manage shutdown explicitly.
- Describe upgrade, receive demand and independent input/output lifecycles.
- Assemble fragments within a size limit.
- Distinguish graceful close, error and abrupt abort.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Use only the included loopback peers and finite known messages. Port 0 selects a test-owned port. Do not expose the fixtures publicly. The runner enforces a process deadline.
Receive one local WebSocket message
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main { static final class Listener implements WebSocket.Listener { final CompletableFuture<String> message = new CompletableFuture<>(); final StringBuilder buffer = new StringBuilder(); public void onOpen(WebSocket socket) { socket.request(1); } public CompletionStage<?> onText(WebSocket socket, CharSequence part, boolean last) { if (part.length() > 16 - buffer.length()) { message.completeExceptionally(new IOException("message too large")); return CompletableFuture.completedFuture(null); } buffer.append(part); if (last) { message.complete(buffer.toString()); buffer.setLength(0); } else socket.request(1); return CompletableFuture.completedFuture(null); } public void onError(WebSocket socket, Throwable error) { message.completeExceptionally(error); } public CompletionStage<?> onClose(WebSocket socket, int code, String reason) { message.completeExceptionally(new EOFException("closed before message")); return CompletableFuture.completedFuture(null); } } // Test-only peer: one upgrade, known ASCII frames, no general protocol parser. static void handshake(Socket peer) throws Exception { InputStream in = peer.getInputStream(); ByteArrayOutputStream header = new ByteArrayOutputStream(); String text = ""; while (header.size() < 4096 && !text.endsWith("\r\n\r\n")) { int b = in.read(); if (b < 0) throw new EOFException(); header.write(b); text = header.toString(StandardCharsets.US_ASCII); } if (!text.endsWith("\r\n\r\n")) throw new IOException("header cap"); String key = Arrays.stream(text.split("\r\n")) .filter(line -> line.regionMatches(true, 0, "Sec-WebSocket-Key:", 0, 18)) .map(line -> line.substring(18).trim()).findFirst().orElseThrow(); // SHA-1 is required by this handshake, not used as authentication. byte[] digest = java.security.MessageDigest.getInstance("SHA-1").digest( (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes(StandardCharsets.US_ASCII)); String reply = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + Base64.getEncoder().encodeToString(digest) + "\r\n\r\n"; peer.getOutputStream().write(reply.getBytes(StandardCharsets.US_ASCII)); } static void frame(Socket peer, int flag, String value) throws IOException { byte[] bytes = value.getBytes(StandardCharsets.US_ASCII); if (bytes.length > 32) throw new IOException("fixture frame cap"); OutputStream out = peer.getOutputStream(); out.write(flag); out.write(bytes.length); out.write(bytes); out.flush(); } static void receive(String first, String second, boolean reject) throws Exception { CountDownLatch release = new CountDownLatch(1); try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")); var worker = Executors.newSingleThreadExecutor()) { server.setSoTimeout(3000); var peer = worker.submit(() -> { try (Socket connection = server.accept()) { connection.setSoTimeout(3000); handshake(connection); frame(connection, second == null ? 0x81 : 0x01, first); if (second != null) frame(connection, 0x80, second); if (!release.await(5, TimeUnit.SECONDS)) throw new IOException("owner deadline"); } return null; }); try (HttpClient client = HttpClient.newBuilder().proxy(ProxySelector.of(null)).build()) { Listener listener = new Listener(); WebSocket socket = client.newWebSocketBuilder().connectTimeout(Duration.ofSeconds(2)) .buildAsync(URI.create("ws://127.0.0.1:" + server.getLocalPort() + "/events"), listener) .get(3, TimeUnit.SECONDS); try { String value = listener.message.get(3, TimeUnit.SECONDS); if (reject) throw new AssertionError("expected size rejection"); System.out.println(value); } catch (ExecutionException ex) { if (!reject || !(ex.getCause() instanceof IOException) || !"message too large".equals(ex.getCause().getMessage())) throw ex; System.out.println("rejected"); } finally { socket.abort(); release.countDown(); } peer.get(3, TimeUnit.SECONDS); } finally { release.countDown(); } } } public static void main(String[] args) throws Exception { receive("ready", null, false); }}Expected output:
readyThe fixed peer performs a local HTTP upgrade then emits one text frame. The listener requests one callback and completes its application future.
Opening and sending
HttpClient.newWebSocketBuilder().buildAsync(uri, listener) returns a future of WebSocket; use ws for the loopback lab and wss with validated TLS for remote production endpoints. A successful connection does not authenticate application messages. sendText(text, last) returns a future for the send operation; wait or compose sends to avoid conflicting pending sends. Successful send does not prove that the peer processed the message.
Receive demand and fragmentation
The listener starts with zero receive demand. onOpen calls request(1); after processing a fragment, request another callback if needed. The last flag marks the final part of a message. The CompletionStage returned by a listener signals completion of its use of callback data, not a new demand allowance. Copy data that must outlive the callback. Keep buffers bounded; a real service also limits bytes, message rates and total assembly time. Per-WebSocket callbacks are serialized, but sharing one listener among connections requires synchronization.
Closing and failures
On normal application shutdown use sendClose(WebSocket.NORMAL_CLOSURE, "done"), await the send and observe peer close with a deadline; the output and input may close separately. onClose receives the status/reason; onError completes outstanding application operations exceptionally. If a peer does not cooperate or data is invalid, abort releases the connection abruptly. The lab tests receive, assembly, rejection and abort, not a full close handshake or general WebSocket implementation. Reconnect with bounded backoff only when the application protocol supports it.
Assemble a fragmented message
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main { static final class Listener implements WebSocket.Listener { final CompletableFuture<String> message = new CompletableFuture<>(); final StringBuilder buffer = new StringBuilder(); public void onOpen(WebSocket socket) { socket.request(1); } public CompletionStage<?> onText(WebSocket socket, CharSequence part, boolean last) { if (part.length() > 16 - buffer.length()) { message.completeExceptionally(new IOException("message too large")); return CompletableFuture.completedFuture(null); } buffer.append(part); if (last) { message.complete(buffer.toString()); buffer.setLength(0); } else socket.request(1); return CompletableFuture.completedFuture(null); } public void onError(WebSocket socket, Throwable error) { message.completeExceptionally(error); } public CompletionStage<?> onClose(WebSocket socket, int code, String reason) { message.completeExceptionally(new EOFException("closed before message")); return CompletableFuture.completedFuture(null); } } // Test-only peer: one upgrade, known ASCII frames, no general protocol parser. static void handshake(Socket peer) throws Exception { InputStream in = peer.getInputStream(); ByteArrayOutputStream header = new ByteArrayOutputStream(); String text = ""; while (header.size() < 4096 && !text.endsWith("\r\n\r\n")) { int b = in.read(); if (b < 0) throw new EOFException(); header.write(b); text = header.toString(StandardCharsets.US_ASCII); } if (!text.endsWith("\r\n\r\n")) throw new IOException("header cap"); String key = Arrays.stream(text.split("\r\n")) .filter(line -> line.regionMatches(true, 0, "Sec-WebSocket-Key:", 0, 18)) .map(line -> line.substring(18).trim()).findFirst().orElseThrow(); // SHA-1 is required by this handshake, not used as authentication. byte[] digest = java.security.MessageDigest.getInstance("SHA-1").digest( (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes(StandardCharsets.US_ASCII)); String reply = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + Base64.getEncoder().encodeToString(digest) + "\r\n\r\n"; peer.getOutputStream().write(reply.getBytes(StandardCharsets.US_ASCII)); } static void frame(Socket peer, int flag, String value) throws IOException { byte[] bytes = value.getBytes(StandardCharsets.US_ASCII); if (bytes.length > 32) throw new IOException("fixture frame cap"); OutputStream out = peer.getOutputStream(); out.write(flag); out.write(bytes.length); out.write(bytes); out.flush(); } static void receive(String first, String second, boolean reject) throws Exception { CountDownLatch release = new CountDownLatch(1); try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")); var worker = Executors.newSingleThreadExecutor()) { server.setSoTimeout(3000); var peer = worker.submit(() -> { try (Socket connection = server.accept()) { connection.setSoTimeout(3000); handshake(connection); frame(connection, second == null ? 0x81 : 0x01, first); if (second != null) frame(connection, 0x80, second); if (!release.await(5, TimeUnit.SECONDS)) throw new IOException("owner deadline"); } return null; }); try (HttpClient client = HttpClient.newBuilder().proxy(ProxySelector.of(null)).build()) { Listener listener = new Listener(); WebSocket socket = client.newWebSocketBuilder().connectTimeout(Duration.ofSeconds(2)) .buildAsync(URI.create("ws://127.0.0.1:" + server.getLocalPort() + "/events"), listener) .get(3, TimeUnit.SECONDS); try { String value = listener.message.get(3, TimeUnit.SECONDS); if (reject) throw new AssertionError("expected size rejection"); System.out.println(value); } catch (ExecutionException ex) { if (!reject || !(ex.getCause() instanceof IOException) || !"message too large".equals(ex.getCause().getMessage())) throw ex; System.out.println("rejected"); } finally { socket.abort(); release.countDown(); } peer.get(3, TimeUnit.SECONDS); } finally { release.countDown(); } } } public static void main(String[] args) throws Exception { receive("stock:", "3", false); }}Expected output:
stock:3The listener uses last rather than assuming each callback is a whole message; transport callback boundaries may differ from frame boundaries.
Reject a message above the cap
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main { static final class Listener implements WebSocket.Listener { final CompletableFuture<String> message = new CompletableFuture<>(); final StringBuilder buffer = new StringBuilder(); public void onOpen(WebSocket socket) { socket.request(1); } public CompletionStage<?> onText(WebSocket socket, CharSequence part, boolean last) { if (part.length() > 16 - buffer.length()) { message.completeExceptionally(new IOException("message too large")); return CompletableFuture.completedFuture(null); } buffer.append(part); if (last) { message.complete(buffer.toString()); buffer.setLength(0); } else socket.request(1); return CompletableFuture.completedFuture(null); } public void onError(WebSocket socket, Throwable error) { message.completeExceptionally(error); } public CompletionStage<?> onClose(WebSocket socket, int code, String reason) { message.completeExceptionally(new EOFException("closed before message")); return CompletableFuture.completedFuture(null); } } // Test-only peer: one upgrade, known ASCII frames, no general protocol parser. static void handshake(Socket peer) throws Exception { InputStream in = peer.getInputStream(); ByteArrayOutputStream header = new ByteArrayOutputStream(); String text = ""; while (header.size() < 4096 && !text.endsWith("\r\n\r\n")) { int b = in.read(); if (b < 0) throw new EOFException(); header.write(b); text = header.toString(StandardCharsets.US_ASCII); } if (!text.endsWith("\r\n\r\n")) throw new IOException("header cap"); String key = Arrays.stream(text.split("\r\n")) .filter(line -> line.regionMatches(true, 0, "Sec-WebSocket-Key:", 0, 18)) .map(line -> line.substring(18).trim()).findFirst().orElseThrow(); // SHA-1 is required by this handshake, not used as authentication. byte[] digest = java.security.MessageDigest.getInstance("SHA-1").digest( (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes(StandardCharsets.US_ASCII)); String reply = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + Base64.getEncoder().encodeToString(digest) + "\r\n\r\n"; peer.getOutputStream().write(reply.getBytes(StandardCharsets.US_ASCII)); } static void frame(Socket peer, int flag, String value) throws IOException { byte[] bytes = value.getBytes(StandardCharsets.US_ASCII); if (bytes.length > 32) throw new IOException("fixture frame cap"); OutputStream out = peer.getOutputStream(); out.write(flag); out.write(bytes.length); out.write(bytes); out.flush(); } static void receive(String first, String second, boolean reject) throws Exception { CountDownLatch release = new CountDownLatch(1); try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")); var worker = Executors.newSingleThreadExecutor()) { server.setSoTimeout(3000); var peer = worker.submit(() -> { try (Socket connection = server.accept()) { connection.setSoTimeout(3000); handshake(connection); frame(connection, second == null ? 0x81 : 0x01, first); if (second != null) frame(connection, 0x80, second); if (!release.await(5, TimeUnit.SECONDS)) throw new IOException("owner deadline"); } return null; }); try (HttpClient client = HttpClient.newBuilder().proxy(ProxySelector.of(null)).build()) { Listener listener = new Listener(); WebSocket socket = client.newWebSocketBuilder().connectTimeout(Duration.ofSeconds(2)) .buildAsync(URI.create("ws://127.0.0.1:" + server.getLocalPort() + "/events"), listener) .get(3, TimeUnit.SECONDS); try { String value = listener.message.get(3, TimeUnit.SECONDS); if (reject) throw new AssertionError("expected size rejection"); System.out.println(value); } catch (ExecutionException ex) { if (!reject || !(ex.getCause() instanceof IOException) || !"message too large".equals(ex.getCause().getMessage())) throw ex; System.out.println("rejected"); } finally { socket.abort(); release.countDown(); } peer.get(3, TimeUnit.SECONDS); } finally { release.countDown(); } } } public static void main(String[] args) throws Exception { receive("1234567890", "1234567890", true); }}Expected output:
rejectedThe aggregate would exceed 16 UTF-16 code units, so the listener completes exceptionally and the owner aborts. This is a character cap, not a wire-byte limit.
Common mistakes
Do not request unlimited callbacks and accumulate indefinitely, block the listener waiting for a future that depends on its own callback, or treat a close-frame send as proof of peer acknowledgement. Never deploy the tiny fixture peer; it is deliberately not a full HTTP or WebSocket server.
Practice
Change the fragmented message to parts event: and 7, keeping the cap and cleanup. Predict the assembled result.
Expected output:
event:7Compare your answer with the manual practice criteria.
Official reading: WebSocket · WebSocket.Listener · WebSocket.Builder · HttpClient. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
WebSocket lifecycle — knowledge check
Original networking and HTTP questions.
What does request(1) grant?
What does last mean in onText?
What does a listener CompletionStage signal?
What does abort do?
Why cap the aggregate buffer?