Java WebSocket Basics
A Java WebSocket is a long-lived, two-way connection between a client and a server. After one HTTP "upgrade" handshake, both sides can send messages at any time, so the server can push data to the client without being asked.
WebSockets power chat apps, live dashboards, multiplayer games, notifications and stock tickers. Since Java 11, the JDK includes a WebSocket client in java.net.http. In this lesson you will connect with it, send and receive text messages, handle every listener event, deal with partial messages and handshake errors, and build a reusable chat client.
How WebSockets Work
A WebSocket starts life as an ordinary HTTP request that asks to switch protocols. If the server agrees, the same TCP connection is kept open and both sides exchange small frames instead of HTTP requests and responses.
| Step | What travels over the connection |
|---|---|
| 1. Handshake request | GET /chat HTTP/1.1 with Upgrade: websocket and a random Sec-WebSocket-Key |
| 2. Handshake response | HTTP/1.1 101 Switching Protocols with a matching Sec-WebSocket-Accept |
| 3. Messages | Text or binary frames, in either direction, at any time |
| 4. Keep-alive | Ping frames, answered with pong frames |
| 5. Closing | Each side sends a close frame with a status code |
| HTTP request/response | WebSocket | |
|---|---|---|
| Who starts a message | Always the client | Client or server |
| Connection | Usually short, one exchange | Stays open for many messages |
| Overhead per message | Full set of headers | 2 to 14 bytes of frame header |
| URI scheme | http://, https:// | ws://, wss:// (encrypted) |
The Java WebSocket API
The Java WebSocket client lives in java.net.http and is created from an HttpClient. It has three main parts.
| Type | Role |
|---|---|
WebSocket.Builder | From httpClient.newWebSocketBuilder(); sets headers, subprotocols and the connect timeout |
WebSocket | The open connection; you call it to send |
WebSocket.Listener | Your callback object; the client calls it when something is received |
WebSocket method | Purpose |
|---|---|
sendText(text, last) | Send a text message (or part of one when last is false) |
sendBinary(buffer, last) | Send binary data |
sendPing(buffer) / sendPong(buffer) | Send control frames |
sendClose(statusCode, reason) | Start the closing handshake |
request(n) | Allow the listener to receive n more events |
abort() | Close the connection at once, without a handshake |
getSubprotocol() | The subprotocol the server chose |
isInputClosed() / isOutputClosed() | Whether each direction is closed |
All send... methods are asynchronous and return a CompletableFuture<WebSocket>. Call join() to wait, or chain the next send with thenCompose(), as shown in Java CompletableFuture.
Note: The JDK only provides a WebSocket client. To run a WebSocket server in Java, you normally use a framework such as Jakarta WebSocket (Tomcat, Jetty) or Spring Boot.
A Local WebSocket Server for the Examples
To keep every example runnable offline, save this ChatServer.java next to the examples. It is a small WebSocket chat server built on a Java ServerSocket: it accepts connections on ws://localhost:8096/chat?name=..., sends a welcome message, broadcasts every text message to all connected users and answers pings and close frames. Any other path gets 404 Not Found.
// FILE: ChatServer.java
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
// A minimal WebSocket chat server on ws://localhost:8096/chat?name=...
// It sends a welcome message and broadcasts every text message to all users.
public class ChatServer {
private static final String GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // fixed by RFC 6455
private static final Set<Connection> USERS = ConcurrentHashMap.newKeySet();
public static ServerSocket start() throws IOException {
ServerSocket server = new ServerSocket(8096, 50, InetAddress.getLoopbackAddress());
Thread.ofVirtual().start(() -> {
while (!server.isClosed()) {
try {
Socket socket = server.accept();
Thread.ofVirtual().start(() -> handle(socket));
} catch (IOException e) {
return;
}
}
});
return server;
}
record Connection(String name, OutputStream out) {
synchronized void sendFrame(int opcode, byte[] payload) throws IOException {
out.write(0x80 | opcode); // FIN + opcode, no mask (server)
if (payload.length < 126) {
out.write(payload.length);
} else {
out.write(126);
out.write(payload.length >> 8);
out.write(payload.length & 0xFF);
}
out.write(payload);
out.flush();
}
void sendText(String text) throws IOException {
sendFrame(0x1, text.getBytes(StandardCharsets.UTF_8));
}
}
private static void handle(Socket socket) {
Connection me = null;
try (socket) {
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
OutputStream out = socket.getOutputStream();
// 1. HTTP upgrade handshake
String requestLine = readLine(in);
Map<String, String> headers = new HashMap<>();
for (String line = readLine(in); !line.isEmpty(); line = readLine(in)) {
int colon = line.indexOf(':');
headers.put(line.substring(0, colon).trim().toLowerCase(), line.substring(colon + 1).trim());
}
URI target = URI.create(requestLine.split(" ")[1]);
if (!target.getPath().equals("/chat") || !headers.containsKey("sec-websocket-key")) {
out.write("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n".getBytes(StandardCharsets.US_ASCII));
return;
}
String accept = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1")
.digest((headers.get("sec-websocket-key") + GUID).getBytes(StandardCharsets.US_ASCII)));
String response = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
+ "Sec-WebSocket-Accept: " + accept + "\r\n";
String offered = headers.getOrDefault("sec-websocket-protocol", "");
if (offered.contains("chat.v1")) response += "Sec-WebSocket-Protocol: chat.v1\r\n";
out.write((response + "\r\n").getBytes(StandardCharsets.US_ASCII));
out.flush();
String query = target.getQuery() == null ? "" : target.getQuery();
String name = query.startsWith("name=") ? query.substring(5) : "guest";
me = new Connection(name, out);
USERS.add(me);
me.sendText("Welcome, " + name + "! Users online: " + USERS.size());
// 2. Frame loop
ByteArrayOutputStream message = new ByteArrayOutputStream();
while (true) {
int b0 = in.readUnsignedByte();
int b1 = in.readUnsignedByte();
boolean fin = (b0 & 0x80) != 0;
int opcode = b0 & 0x0F;
long length = b1 & 0x7F;
if (length == 126) length = in.readUnsignedShort();
else if (length == 127) length = in.readLong();
byte[] mask = new byte[4];
in.readFully(mask); // client frames are always masked
byte[] payload = new byte[(int) length];
in.readFully(payload);
for (int i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4];
switch (opcode) {
case 0x0, 0x1 -> { // text (or continuation)
message.write(payload);
if (fin) {
String text = message.toString(StandardCharsets.UTF_8);
message.reset();
for (Connection user : USERS) user.sendText(name + ": " + text);
}
}
case 0x8 -> { // close: echo it and stop
me.sendFrame(0x8, payload);
return;
}
case 0x9 -> me.sendFrame(0xA, payload); // ping -> pong
default -> { } // ignore pong and binary
}
}
} catch (Exception e) {
// connection lost
} finally {
if (me != null) USERS.remove(me);
}
}
private static String readLine(DataInputStream in) throws IOException {
StringBuilder line = new StringBuilder();
int c;
while ((c = in.read()) != '\n') {
if (c == -1) throw new IOException("closed");
if (c != '\r') line.append((char) c);
}
return line.toString();
}
}
You do not need to study the server to follow this lesson, but it shows what the handshake and frames look like on the wire. The Sec-WebSocket-Accept value is a SHA-1 hash of the client's key plus a fixed GUID, which proves the server really speaks WebSocket.
Connecting a Java WebSocket and Sending Messages
To connect, build a WebSocket with buildAsync(uri, listener). The listener receives incoming messages; the returned WebSocket is what you use to send. This client connects, reads the welcome message, sends one message, reads the broadcast and closes.
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class FirstWebSocket {
public static void main(String[] args) throws Exception {
ServerSocket server = ChatServer.start();
LinkedBlockingQueue<String> received = new LinkedBlockingQueue<>();
// The listener is called by the client when something arrives
WebSocket.Listener listener = new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("Connected");
webSocket.request(1); // ask for the first message
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
received.add(data.toString());
webSocket.request(1); // ready for the next message
return null; // null = we are done with 'data'
}
};
try (HttpClient client = HttpClient.newHttpClient()) {
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create("ws://localhost:8096/chat?name=Meena"), listener)
.join(); // wait until the handshake is done
System.out.println("Server: " + received.poll(2, TimeUnit.SECONDS)); // welcome message
webSocket.sendText("Hello WebSocket!", true).join();
System.out.println("Server: " + received.poll(2, TimeUnit.SECONDS));
webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "bye").join();
System.out.println("Output closed? " + webSocket.isOutputClosed());
} finally {
server.close();
}
}
}
Output:
Connected
Server: Welcome, Meena! Users online: 1
Server: Meena: Hello WebSocket!
Output closed? true
How it works:
buildAsync()starts the handshake and returns aCompletableFuture<WebSocket>.join()waits until the connection is open.onOpen()runs once the connection is ready. CallingwebSocket.request(1)there tells the client "I am ready for one message".- Each received text message calls
onText(). The listener copies it into aLinkedBlockingQueue, and the main thread takes it out withpoll(2, SECONDS), which waits up to 2 seconds. sendText("Hello WebSocket!", true)sends a whole message (lastistrue). The server broadcasts it back asMeena: Hello WebSocket!.sendClose(NORMAL_CLOSURE, "bye")sends close code1000and closes the output side.
Note: If you never call
request(n), the listener receives nothing. This flow control lets a slow consumer stop the server from flooding it: you only ask for more messages when you are ready.
WebSocket.Listener Events, Pings and Subprotocols
WebSocket.Listener has a method for every event. All methods have default implementations, so you override only the ones you need.
| Listener method | Called when |
|---|---|
onOpen(ws) | The connection is open |
onText(ws, data, last) | A text message (or part of one) arrives |
onBinary(ws, data, last) | Binary data arrives |
onPing(ws, message) | A ping arrives (the client answers with a pong for you) |
onPong(ws, message) | A pong arrives, usually in answer to your sendPing() |
onClose(ws, statusCode, reason) | The other side sent a close frame |
onError(ws, error) | The connection failed; no more events follow |
The builder can also add handshake headers (for example an auth token) and offer subprotocols: application-level protocol names the server may pick from.
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
public class ListenerEvents {
public static void main(String[] args) throws Exception {
ServerSocket server = ChatServer.start();
CompletableFuture<Void> closed = new CompletableFuture<>();
WebSocket.Listener logger = new WebSocket.Listener() {
@Override
public void onOpen(WebSocket ws) {
System.out.println("onOpen subprotocol='" + ws.getSubprotocol() + "'");
ws.request(1);
}
@Override
public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
System.out.println("onText " + data + " (last part? " + last + ")");
ws.request(1);
return null;
}
@Override
public CompletionStage<?> onPong(WebSocket ws, ByteBuffer message) {
System.out.println("onPong " + StandardCharsets.UTF_8.decode(message));
ws.request(1);
return null;
}
@Override
public CompletionStage<?> onClose(WebSocket ws, int statusCode, String reason) {
System.out.println("onClose status=" + statusCode + " reason='" + reason + "'");
closed.complete(null);
return null;
}
@Override
public void onError(WebSocket ws, Throwable error) {
System.out.println("onError " + error);
closed.completeExceptionally(error);
}
};
try (HttpClient client = HttpClient.newHttpClient()) {
WebSocket ws = client.newWebSocketBuilder()
.header("X-Client-Version", "2.4") // extra handshake header
.subprotocols("chat.v1") // ask for an application protocol
.buildAsync(URI.create("ws://localhost:8096/chat?name=Arjun"), logger)
.join();
Thread.sleep(200);
ws.sendPing(ByteBuffer.wrap("are you alive?".getBytes(StandardCharsets.UTF_8))).join();
Thread.sleep(200);
ws.sendText("first", true).join();
Thread.sleep(200);
ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
closed.join(); // wait for the server's close frame
System.out.println("Input closed? " + ws.isInputClosed() + ", output closed? " + ws.isOutputClosed());
} finally {
server.close();
}
}
}
Output:
onOpen subprotocol='chat.v1'
onText Welcome, Arjun! Users online: 1 (last part? true)
onPong are you alive?
onText Arjun: first (last part? true)
onClose status=1000 reason='done'
Input closed? true, output closed? true
How it works:
.header("X-Client-Version", "2.4")adds a header to the handshake request, the usual place for anAuthorizationtoken..subprotocols("chat.v1")offers a subprotocol. The server accepted it, sogetSubprotocol()returnschat.v1; it would be an empty string if the server chose none.sendPing()sends a ping with a payload. The server answers with a pong carrying the same bytes, which arrive inonPong(). Pings are a cheap way to check that an idle connection is still alive.- After
sendClose(), the server replies with its own close frame.onClose()receives status1000and the reason, and the program waits for it with theclosedfuture. - Both
isInputClosed()andisOutputClosed()aretrueonce the closing handshake is complete.
| Common close code | Constant / meaning |
|---|---|
1000 | WebSocket.NORMAL_CLOSURE: finished normally |
1001 | Going away (server shutting down, page closed) |
1008 | Policy violation (for example, not allowed) |
1011 | Unexpected server error |
Handling Partial and Long Messages
A message may arrive in several parts: onText() is called once for each part, and only the final call has last == true. Large messages are often split this way, and a sender may also split a message on purpose by passing last = false. A robust listener collects parts until last is true.
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class PartialMessages {
// Collects message parts until 'last' is true, then delivers the whole message
static class WholeMessageListener implements WebSocket.Listener {
final LinkedBlockingQueue<String> messages = new LinkedBlockingQueue<>();
private final StringBuilder buffer = new StringBuilder();
@Override
public void onOpen(WebSocket ws) {
ws.request(1);
}
@Override
public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
buffer.append(data); // copy now: 'data' may be reused after we return
if (last) {
messages.add(buffer.toString());
buffer.setLength(0);
}
ws.request(1);
return null;
}
}
public static void main(String[] args) throws Exception {
ServerSocket server = ChatServer.start();
WholeMessageListener listener = new WholeMessageListener();
try (HttpClient client = HttpClient.newHttpClient()) {
WebSocket ws = client.newWebSocketBuilder()
.buildAsync(URI.create("ws://localhost:8096/chat?name=Kavya"), listener)
.join();
listener.messages.poll(2, TimeUnit.SECONDS); // skip the welcome message
// Send one message in three parts; only the last call has last = true
ws.sendText("Order #1042 ", false)
.thenCompose(w -> w.sendText("is packed ", false))
.thenCompose(w -> w.sendText("and shipped.", true))
.join();
System.out.println("Received: " + listener.messages.poll(2, TimeUnit.SECONDS));
// A long message (5,000 characters) is also delivered whole
ws.sendText("x".repeat(5000), true).join();
String longMessage = listener.messages.poll(2, TimeUnit.SECONDS);
System.out.println("Long message length: " + longMessage.length());
ws.sendClose(WebSocket.NORMAL_CLOSURE, "").join();
} finally {
server.close();
}
}
}
Output:
Received: Kavya: Order #1042 is packed and shipped.
Long message length: 5007
How it works:
- The three
sendText()calls form one message, because only the last one passestrue.thenCompose()makes sure each part is sent only after the previous one is done, since a WebSocket allows one outstanding send at a time. - The server receives the parts as continuation frames and broadcasts one combined message.
WholeMessageListenerappends every part to aStringBuilderand publishes the message only whenlastistrue. That is why the 5,000-character message (plus theKavya:prefix, 5,007 characters) arrives whole, however the client splits it internally.- The
datapassed toonText()must be copied before the method returns, because the client may reuse it.
Note: Never assume one
onText()call equals one message. Always checklast, or you will eventually process half a JSON document.
Handling WebSocket Connection Errors
Connection problems surface when you join() the future from buildAsync(). The real error is wrapped in a CompletionException, so check getCause().
| Cause | Meaning |
|---|---|
WebSocketHandshakeException | The server answered, but not with 101 Switching Protocols; getResponse() gives the HTTP response |
ConnectException | Nothing listens on that host and port |
HttpTimeoutException | The connect timeout expired |
IllegalArgumentException | The URI is not ws:// or wss:// |
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.net.http.WebSocketHandshakeException;
import java.time.Duration;
import java.util.concurrent.CompletionException;
public class HandshakeError {
static void tryConnect(HttpClient client, String url) {
try {
WebSocket ws = client.newWebSocketBuilder()
.connectTimeout(Duration.ofSeconds(3))
.buildAsync(URI.create(url), new WebSocket.Listener() { })
.join();
System.out.println(url + " -> connected");
ws.abort(); // close at once; this demo only tests the handshake
} catch (CompletionException e) {
Throwable cause = e.getCause(); // the real error is wrapped
if (cause instanceof WebSocketHandshakeException handshake) {
System.out.println(url + " -> handshake rejected, HTTP status "
+ handshake.getResponse().statusCode());
} else if (cause instanceof ConnectException) {
System.out.println(url + " -> no server listening");
} else {
System.out.println(url + " -> " + cause);
}
}
}
public static void main(String[] args) throws Exception {
ServerSocket server = ChatServer.start();
try (HttpClient client = HttpClient.newHttpClient()) {
tryConnect(client, "ws://localhost:8096/chat"); // correct path
tryConnect(client, "ws://localhost:8096/news"); // server answers 404
tryConnect(client, "ws://localhost:8097/chat"); // nothing on this port
} finally {
server.close();
}
// WebSocket URIs must use ws:// or wss://
try (HttpClient client = HttpClient.newHttpClient()) {
client.newWebSocketBuilder()
.buildAsync(URI.create("http://localhost:8096/chat"), new WebSocket.Listener() { })
.join();
} catch (CompletionException e) {
System.out.println("http://localhost:8096/chat -> " + e.getCause().getMessage());
}
}
}
Output:
ws://localhost:8096/chat -> connected
ws://localhost:8096/news -> handshake rejected, HTTP status 404
ws://localhost:8097/chat -> no server listening
http://localhost:8096/chat -> invalid URI scheme: http
How it works:
- The first URL is a real WebSocket endpoint, so the connection opens.
abort()closes it at once, because this demo only tests the handshake. /newsis not a WebSocket endpoint: the server answers404, andWebSocketHandshakeException.getResponse().statusCode()reveals it.- Port 8097 has no server, so the cause is
ConnectException. - An
http://URI is rejected because WebSockets requirews://orwss://. HttpClient.close()waits for open WebSockets to finish. Always close or abort every WebSocket before closing the client, or the program will wait forever.
Real-World Example: A WebSocket Chat Client
A real application wraps the WebSocket in a class with simple methods, so the rest of the code never deals with listeners or futures. This ChatClient:
- connects with a connect timeout and URL-encodes the user name,
- collects message parts into whole messages and puts them in an inbox queue,
- offers
say(),nextMessage()andmessages()methods, - closes with the proper handshake, and aborts if the server does not answer.
Two users, Asha and Vikram, chat through the local server.
import java.net.ServerSocket;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
// A reusable WebSocket chat client: send messages, wait for messages, close cleanly
public class ChatClient implements AutoCloseable {
private final String name;
private final WebSocket webSocket;
private final LinkedBlockingQueue<String> inbox = new LinkedBlockingQueue<>();
private final CompletableFuture<Integer> closeStatus = new CompletableFuture<>();
private final StringBuilder partial = new StringBuilder();
public ChatClient(HttpClient httpClient, String baseUrl, String name) {
this.name = name;
String url = baseUrl + "?name=" + URLEncoder.encode(name, StandardCharsets.UTF_8);
this.webSocket = httpClient.newWebSocketBuilder()
.connectTimeout(Duration.ofSeconds(3))
.buildAsync(URI.create(url), new Listener())
.join();
}
private class Listener implements WebSocket.Listener {
@Override
public void onOpen(WebSocket ws) {
ws.request(1);
}
@Override
public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
partial.append(data);
if (last) {
inbox.add(partial.toString());
partial.setLength(0);
}
ws.request(1);
return null;
}
@Override
public CompletionStage<?> onClose(WebSocket ws, int statusCode, String reason) {
closeStatus.complete(statusCode);
return null;
}
@Override
public void onError(WebSocket ws, Throwable error) {
closeStatus.completeExceptionally(error);
}
}
public void say(String text) {
webSocket.sendText(text, true).join();
}
// Wait for the next message, or return null after the timeout
public String nextMessage(Duration timeout) throws InterruptedException {
return inbox.poll(timeout.toMillis(), TimeUnit.MILLISECONDS);
}
// Collect messages until 'count' have arrived or the time is up
public List<String> messages(int count, Duration timeout) throws InterruptedException {
List<String> result = new ArrayList<>();
long deadline = System.nanoTime() + timeout.toNanos();
while (result.size() < count) {
long left = deadline - System.nanoTime();
String message = inbox.poll(Math.max(left, 0), TimeUnit.NANOSECONDS);
if (message == null) break;
result.add(message);
}
return result;
}
@Override
public void close() {
if (!webSocket.isOutputClosed()) {
webSocket.sendClose(WebSocket.NORMAL_CLOSURE, name + " left").join();
}
try {
int status = closeStatus.get(2, TimeUnit.SECONDS);
System.out.println("[" + name + " disconnected, status " + status + "]");
} catch (Exception e) {
webSocket.abort(); // server did not answer: drop the connection
System.out.println("[" + name + " aborted]");
}
}
public static void main(String[] args) throws Exception {
ServerSocket server = ChatServer.start();
String url = "ws://localhost:8096/chat";
try (HttpClient http = HttpClient.newHttpClient();
ChatClient asha = new ChatClient(http, url, "Asha")) {
System.out.println("Asha sees: " + asha.nextMessage(Duration.ofSeconds(2)));
try (ChatClient vikram = new ChatClient(http, url, "Vikram")) {
System.out.println("Vikram sees: " + vikram.nextMessage(Duration.ofSeconds(2)));
asha.say("Hi Vikram, is the build green?");
System.out.println("Vikram sees: " + vikram.nextMessage(Duration.ofSeconds(2)));
vikram.say("Yes, all 214 tests passed.");
System.out.println("Asha sees: " + asha.messages(2, Duration.ofSeconds(2)));
}
asha.say("Anyone still here?");
System.out.println("Asha sees: " + asha.messages(5, Duration.ofMillis(500)));
} finally {
server.close();
}
}
}
Output:
Asha sees: Welcome, Asha! Users online: 1
Vikram sees: Welcome, Vikram! Users online: 2
Vikram sees: Asha: Hi Vikram, is the build green?
Asha sees: [Asha: Hi Vikram, is the build green?, Vikram: Yes, all 214 tests passed.]
[Vikram disconnected, status 1000]
Asha sees: [Asha: Anyone still here?]
[Asha disconnected, status 1000]
How it works:
- Hidden listener. The private inner
Listenerclass handles events and writes complete messages to theinboxqueue. Callers only seesay(),nextMessage()andmessages(). - Server push. When Asha speaks, the server pushes the message to both users without anyone asking. Asha sees her own message too, because the server broadcasts to everybody.
- Waiting with deadlines.
messages(count, timeout)collects up tocountmessages but stops at the deadline. After Vikram leaves, Asha asks for 5 messages within 500 ms and gets only the one that exists, instead of blocking forever. - Safe names.
URLEncoder.encode(name, UTF_8)keeps names with spaces or symbols from breaking the URI, as explained in the Java URI class lesson. - Clean closing.
close()sends a close frame, then waits up to 2 seconds foronClose()to completecloseStatus. If the server never answers,abort()drops the connection so the program cannot hang. - Nested lifetimes. Try-with-resources closes Vikram's client first and then Asha's, and the
HttpClientis closed last, after every WebSocket has finished.
The same structure works with any WebSocket service: change the URL, add an Authorization header in the builder, and parse each message (often JSON) when it comes out of the inbox.