WebSockets
suggest changeHTTP is request/response: the client asks, the server answers, and the server can't send anything on its own. A WebSocket is a long-lived, two-way connection. It starts as an ordinary HTTP request that asks the server to "upgrade" the connection. After that, both sides can send messages at any time over the same TCP connection, with only 2 to 14 bytes of framing per message. Chat, live dashboards, multiplayer games, notifications and collaborative editors all use WebSockets.
What Java gives you:
| Side | Option | Notes |
|---|---|---|
| Client | java.net.http.WebSocket |
Built into the JDK since Java 11. No dependencies |
| Server | Java-WebSocket | Small library (one jar plus SLF4J). Used in this article |
| Server | Jakarta WebSocket (@ServerEndpoint) |
The standard API in Jetty, Tomcat, Undertow, Tyrus |
| Server | Spring (WebSocketHandler, STOMP) |
When the app is already a Spring Boot app |
The JDK has a WebSocket client but no WebSocket server: the built-in com.sun.net.httpserver.HttpServer can't upgrade connections. The examples below use Java-WebSocket 1.6.0 for the server side and the JDK client for the client side. Every example is a single file you can run with the source launcher. Put the jars in a lib directory:
lib/Java-WebSocket-1.6.0.jar
lib/slf4j-api-2.0.17.jar
lib/slf4j-nop-2.0.17.jar (optional: silences SLF4J's "no provider" warning)
and run with:
java -cp "lib/*" EchoClient.java
With Maven or Gradle, the dependency is org.java-websocket:Java-WebSocket:1.6.0. All output below comes from JDK 25.
For plain TCP see Basic Client and Server Communication using a Socket. For request/response HTTP see REST APIs and HTTP headers.
How the protocol works
A WebSocket connection begins with an HTTP/1.1 GET request carrying these headers:
GET /chat HTTP/1.1
Host: localhost:8080
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
If the server accepts, it answers 101 Switching Protocols and from then on the TCP connection carries WebSocket frames instead of HTTP. Sec-WebSocket-Key is 16 random bytes in Base64. The server proves it understands WebSockets by sending back Sec-WebSocket-Accept: the SHA-1 hash of the key concatenated with a fixed GUID, in Base64. It's not a security feature. It only stops plain HTTP servers and caches from accepting the upgrade by accident.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
public class AcceptKey {
static final String GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static String accept(String key) throws Exception {
byte[] sha1 = MessageDigest.getInstance("SHA-1")
.digest((key + GUID).getBytes(StandardCharsets.US_ASCII));
return Base64.getEncoder().encodeToString(sha1);
}
public static void main(String[] args) throws Exception {
// the sample key from RFC 6455, section 1.3
String key = "dGhlIHNhbXBsZSBub25jZQ==";
System.out.println("Sec-WebSocket-Key: " + key);
System.out.println("Sec-WebSocket-Accept: " + accept(key));
}
}
Output:
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
After the handshake, data travels in messages. A message is either text (UTF-8) or binary and may be split into several frames. There are also three control frames:
| Frame | Purpose |
|---|---|
| Ping | "Are you still there?" Payload up to 125 bytes |
| Pong | Reply to a ping, with the same payload. The JDK and Java-WebSocket send it automatically |
| Close | Starts the closing handshake. Carries a status code and an optional reason |
The URL scheme is ws:// for plain connections and wss:// for WebSocket over TLS. Use wss:// for anything outside your own machine: it is encrypted, and proxies are less likely to break it.
An echo server
A server extends WebSocketServer and implements callbacks for the connection lifecycle. onMessage(WebSocket, String) handles text messages. Override onMessage(WebSocket, ByteBuffer) to handle binary messages, otherwise they are ignored.
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class EchoServer extends WebSocketServer {
public EchoServer(int port) {
super(new InetSocketAddress("localhost", port));
setReuseAddr(true);
}
@Override
public void onStart() {
System.out.println("listening on ws://localhost:" + getPort());
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("open " + conn.getRemoteSocketAddress()
+ " path=" + handshake.getResourceDescriptor());
conn.send("welcome");
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("text: " + message);
conn.send("echo: " + message);
}
@Override
public void onMessage(WebSocket conn, ByteBuffer bytes) {
System.out.println("binary: " + bytes.remaining() + " bytes");
conn.send(bytes);
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("close " + code + " '" + reason + "' remote=" + remote);
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.out.println("error: " + ex);
}
public static void main(String[] args) {
new EchoServer(8080).start();
}
}
start() returns immediately and runs the server on its own thread. onStart() is called once the socket is bound. The callbacks for all connections run on the server's few worker threads, so don't block in them: a slow onMessage delays every other client served by that thread.
You can talk to the server by hand to see the handshake. Start EchoServer and run:
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class RawHandshake {
public static void main(String[] args) throws Exception {
try (Socket s = new Socket("localhost", 8080)) {
Writer out = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.US_ASCII);
out.write("GET /chat HTTP/1.1\r\n"
+ "Host: localhost:8080\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
+ "Sec-WebSocket-Version: 13\r\n"
+ "\r\n");
out.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream(), StandardCharsets.US_ASCII));
String line;
while (!(line = in.readLine()).isEmpty()) {
System.out.println(line);
}
}
}
}
Output:
HTTP/1.1 101 Web Socket Protocol Handshake
Connection: Upgrade
Date: Sat, 17 Oct 2026 19:26:37 GMT
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Server: TooTallNate Java-WebSocket
Upgrade: websocket
The accept value matches the one computed above. Because the program exits without sending a Close frame, the server logs close 1006 '' remote=true. Code 1006 means "the connection dropped without a closing handshake".
A client with java.net.http.WebSocket
You create the JDK client from an HttpClient. You pass a WebSocket.Listener that receives events, and buildAsync() returns a CompletableFuture<WebSocket> that completes when the handshake succeeds.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
public class EchoClient {
public static void main(String[] args) throws Exception {
CountDownLatch replies = new CountDownLatch(3); // welcome + 2 echoes
CompletableFuture<Void> closed = new CompletableFuture<>();
WebSocket.Listener listener = new WebSocket.Listener() {
@Override
public void onOpen(WebSocket ws) {
System.out.println("connected, subprotocol='" + ws.getSubprotocol() + "'");
ws.request(1); // ask for the first message
}
@Override
public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
System.out.println("received text: " + data);
replies.countDown();
ws.request(1); // ready for the next message
return null;
}
@Override
public CompletionStage<?> onBinary(WebSocket ws, ByteBuffer data, boolean last) {
System.out.println("received binary: " + data.remaining() + " bytes");
replies.countDown();
ws.request(1);
return null;
}
@Override
public CompletionStage<?> onClose(WebSocket ws, int statusCode, String reason) {
System.out.println("closed by server: " + statusCode + " " + reason);
closed.complete(null);
return null;
}
@Override
public void onError(WebSocket ws, Throwable error) {
System.out.println("error: " + error);
closed.completeExceptionally(error);
}
};
HttpClient client = HttpClient.newHttpClient();
WebSocket ws = client.newWebSocketBuilder()
.connectTimeout(Duration.ofSeconds(5))
.buildAsync(URI.create("ws://localhost:8080/echo"), listener)
.join();
ws.sendText("hello", true).join();
ws.sendBinary(ByteBuffer.wrap(new byte[] {1, 2, 3, 4}), true).join();
replies.await();
ws.sendClose(WebSocket.NORMAL_CLOSURE, "bye").join();
closed.join(); // wait for the server's close frame
System.out.println("isInputClosed=" + ws.isInputClosed()
+ " isOutputClosed=" + ws.isOutputClosed());
}
}
With EchoServer running, the client prints:
connected, subprotocol=''
received text: welcome
received text: echo: hello
received binary: 4 bytes
closed by server: 1000 bye
isInputClosed=true isOutputClosed=true
and the server prints:
listening on ws://localhost:8080
open /127.0.0.1:57517 path=/echo
text: hello
binary: 4 bytes
close 1000 'bye' remote=true
How the listener works:
- Flow control with
request(n). TheWebSocketdelivers only as many messages as you ask for.request(1)inonOpenasks for the first one, and every handler asks for the next. If you forget, the listener stops receiving and nothing seems to happen. The defaultListenermethods (the ones you don't override) callrequest(1)for you, sonew WebSocket.Listener() {}is a valid listener that receives and drops everything. - The returned
CompletionStage. Returningnullmeans "I'm done withdata". If you process data asynchronously, return a stage that completes when you're finished. TheWebSocketmay reuse theCharSequenceorByteBufferafter that, so copy the data if you need to keep it. - Callbacks are sequential. The listener is never called concurrently, so its own fields don't need synchronization.
- Sends are asynchronous.
sendText,sendBinary,sendPingandsendClosereturn aCompletableFuture<WebSocket>that completes when the data has been written to the socket.
Large and fragmented messages
The last argument of onText and onBinary says whether this is the final part of a message. The JDK splits large messages into several calls, so a listener that handles messages bigger than a few KB must collect the parts:
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class PartialMessages {
public static void main(String[] args) throws Exception {
CountDownLatch started = new CountDownLatch(1);
WebSocketServer server = new WebSocketServer(new InetSocketAddress("localhost", 0)) {
public void onStart() { started.countDown(); }
public void onOpen(org.java_websocket.WebSocket c, ClientHandshake h) {
c.send("x".repeat(200_000)); // one big text message
c.send("small");
}
public void onMessage(org.java_websocket.WebSocket c, String msg) {
System.out.println("server got " + msg.length() + " chars: " + msg);
}
public void onClose(org.java_websocket.WebSocket c, int code, String r, boolean remote) {}
public void onError(org.java_websocket.WebSocket c, Exception e) { e.printStackTrace(); }
};
server.start();
started.await();
CountDownLatch done = new CountDownLatch(2);
WebSocket.Listener listener = new WebSocket.Listener() {
final StringBuilder buf = new StringBuilder();
int parts;
public void onOpen(WebSocket ws) { ws.request(1); }
public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
buf.append(data);
parts++;
if (last) {
String msg = buf.toString();
System.out.println("message of " + msg.length() + " chars in " + parts + " part(s)");
buf.setLength(0);
parts = 0;
done.countDown();
}
ws.request(1);
return null;
}
};
WebSocket ws = HttpClient.newHttpClient().newWebSocketBuilder()
.buildAsync(URI.create("ws://localhost:" + server.getPort()), listener)
.join();
done.await();
// send one message as three fragments
ws.sendText("Hello, ", false).join();
ws.sendText("fragmented ", false).join();
ws.sendText("world", true).join();
Thread.sleep(200);
ws.sendClose(WebSocket.NORMAL_CLOSURE, "").join();
server.stop(1000);
}
}
Output (the number of parts depends on buffer sizes and timing):
message of 200000 chars in 13 part(s)
message of 5 chars in 1 part(s)
server got 23 chars: Hello, fragmented world
The other direction works the same way: sendText(part, false) sends a fragment and sendText(part, true) ends the message. That lets you stream a large message without building it in memory first. Java-WebSocket puts the fragments back together, so the server's onMessage sees one string.
The example uses the fully qualified org.java_websocket.WebSocket because both libraries call their interface WebSocket. In a real project the server and the client normally live in different files.
Sending from several threads
java.net.http.WebSocket allows only one pending data send at a time. If you call sendText before the future of the previous sendText or sendBinary has completed, the new future fails with IllegalStateException. This shows up as soon as several threads write to the same socket, for example when a client forwards events from many sources. The fix is to chain each send onto the previous one:
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class ConcurrentSends {
// Serializes sends: each one starts after the previous one completes
static final class SerialSender {
private final WebSocket ws;
private CompletableFuture<WebSocket> tail;
SerialSender(WebSocket ws) {
this.ws = ws;
this.tail = CompletableFuture.completedFuture(ws);
}
synchronized CompletableFuture<WebSocket> sendText(String text) {
tail = tail.thenCompose(w -> w.sendText(text, true));
return tail;
}
}
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
public static void main(String[] args) throws Exception {
AtomicInteger received = new AtomicInteger();
CountDownLatch started = new CountDownLatch(1);
WebSocketServer server = new WebSocketServer(new InetSocketAddress("localhost", 0)) {
public void onStart() { started.countDown(); }
public void onOpen(org.java_websocket.WebSocket c, ClientHandshake h) {}
public void onMessage(org.java_websocket.WebSocket c, String msg) {
if (msg.equals("pause")) {
sleep(1000); // a slow server: stops reading for a second
} else {
received.incrementAndGet();
}
}
public void onClose(org.java_websocket.WebSocket c, int code, String r, boolean remote) {}
public void onError(org.java_websocket.WebSocket c, Exception e) {}
};
server.start();
started.await();
WebSocket ws = HttpClient.newHttpClient().newWebSocketBuilder()
.buildAsync(URI.create("ws://localhost:" + server.getPort()), new WebSocket.Listener() {})
.join();
ws.sendText("pause", true).join();
// Wrong: start a new send before the previous one has completed
String big = "x".repeat(10_000_000);
CompletableFuture<WebSocket> first = ws.sendText(big, true);
System.out.println("first done? " + first.isDone());
CompletableFuture<WebSocket> second = ws.sendText(big, true);
second.exceptionally(e -> {
System.out.println("second send failed: " + e);
return null;
}).join();
first.join();
// Right: funnel all sends through one serializing sender
SerialSender sender = new SerialSender(ws);
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1000; i++) {
int n = i;
pool.submit(() -> sender.sendText("message " + n));
}
}
sender.sendText("last").join();
Thread.sleep(500);
System.out.println("server received " + received.get() + " messages");
ws.sendClose(WebSocket.NORMAL_CLOSURE, "").join();
server.stop(1000);
}
}
Output:
first done? false
second send failed: java.lang.IllegalStateException: Send pending
server received 1002 messages
The "pause" message makes the server stop reading for a second, so the 10 MB message can't be written right away and the second send hits a pending one. The server counts the first big message, the 1000 messages from the virtual threads and last.
SerialSender builds a chain of futures, so each send starts only after the previous one finished. The synchronized method makes updating tail safe across threads, and messages go out in the order they reached sendText. A real app should also limit how many messages may be queued, because a slow peer makes the chain grow without bound.
Java-WebSocket's conn.send() and broadcast() are thread-safe and queue internally, so this applies only to the JDK client.
Handshake: headers, query parameters and subprotocols
Everything the client wants to say before the connection opens goes into the handshake request:
- URL path and query, e.g.
ws://host/rooms/42?user=alice - Headers, e.g.
Authorizationwith a token. Browsers can't set headers on WebSocket requests, so browser clients often send a token in the query string or as a cookie instead - Subprotocols: the
Sec-WebSocket-Protocolheader lists application protocols in order of preference, and the server picks one
A server can check the request and refuse the connection before it opens. In Java-WebSocket, override onWebsocketHandshakeReceivedAsServer and throw InvalidDataException:
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.net.http.WebSocketHandshakeException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CountDownLatch;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.ServerHandshakeBuilder;
import org.java_websocket.protocols.Protocol;
import org.java_websocket.server.WebSocketServer;
public class HandshakeAuth {
public static void main(String[] args) throws Exception {
// the server speaks only the "chat.v2" subprotocol
Draft draft = new Draft_6455(Collections.emptyList(), List.of(new Protocol("chat.v2")));
CountDownLatch started = new CountDownLatch(1);
WebSocketServer server = new WebSocketServer(new InetSocketAddress("localhost", 0), List.of(draft)) {
@Override
public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(
org.java_websocket.WebSocket conn, Draft d, ClientHandshake request)
throws InvalidDataException {
ServerHandshakeBuilder response = super.onWebsocketHandshakeReceivedAsServer(conn, d, request);
if (!"Bearer secret-token".equals(request.getFieldValue("Authorization"))) {
System.out.println("server: rejecting, bad token");
throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "bad token");
}
return response;
}
public void onStart() { started.countDown(); }
public void onOpen(org.java_websocket.WebSocket c, ClientHandshake h) {
System.out.println("server: open " + h.getResourceDescriptor()
+ " protocol=" + h.getFieldValue("Sec-WebSocket-Protocol"));
}
public void onMessage(org.java_websocket.WebSocket c, String msg) {}
public void onClose(org.java_websocket.WebSocket c, int code, String r, boolean remote) {}
public void onError(org.java_websocket.WebSocket c, Exception e) {}
};
server.start();
started.await();
URI uri = URI.create("ws://localhost:" + server.getPort() + "/rooms/42?user=alice");
HttpClient client = HttpClient.newHttpClient();
// 1. correct token
WebSocket ws = client.newWebSocketBuilder()
.header("Authorization", "Bearer secret-token")
.subprotocols("chat.v3", "chat.v2") // in order of preference
.buildAsync(uri, new WebSocket.Listener() {})
.join();
System.out.println("client: connected, subprotocol=" + ws.getSubprotocol());
ws.sendClose(WebSocket.NORMAL_CLOSURE, "").join();
// 2. wrong token
try {
client.newWebSocketBuilder()
.header("Authorization", "Bearer wrong")
.subprotocols("chat.v2")
.buildAsync(uri, new WebSocket.Listener() {})
.join();
} catch (CompletionException e) {
if (e.getCause() instanceof WebSocketHandshakeException hs) {
System.out.println("client: handshake rejected, HTTP " + hs.getResponse().statusCode());
} else {
System.out.println("client: " + e.getCause());
}
}
server.stop(1000);
}
}
Output:
server: open /rooms/42?user=alice protocol=chat.v3, chat.v2
client: connected, subprotocol=chat.v2
server: rejecting, bad token
client: handshake rejected, HTTP 404
When the handshake fails, buildAsync() completes exceptionally with a WebSocketHandshakeException. Its getResponse() returns the HTTP response, so the client can tell an auth error from a network error. Java-WebSocket always answers a rejected handshake with 404. Jakarta WebSocket and Spring let you choose the status, for example 401 or 403.
You can't set the headers the client manages itself (Sec-WebSocket-Key, Sec-WebSocket-Protocol, Upgrade, Connection and others): header() accepts them, but the future from buildAsync() then fails with IllegalArgumentException. Use subprotocols() to offer subprotocols.
Ping, pong and closing
NATs, load balancers and proxies drop idle connections, often after 30 to 120 seconds. Pings keep connections alive and detect dead peers. Java-WebSocket pings every client and closes connections that don't answer within setConnectionLostTimeout(seconds) (default 60). The JDK client answers pings automatically and calls onPing so you can see them. You can also send your own pings, for example to measure latency:
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class PingPong {
public static void main(String[] args) throws Exception {
CountDownLatch started = new CountDownLatch(1);
WebSocketServer server = new WebSocketServer(new InetSocketAddress("localhost", 0)) {
public void onStart() { started.countDown(); }
public void onOpen(org.java_websocket.WebSocket c, ClientHandshake h) {}
public void onMessage(org.java_websocket.WebSocket c, String msg) {
if (msg.equals("quit")) {
c.close(4000, "client asked to quit"); // 4000-4999: application codes
}
}
public void onClose(org.java_websocket.WebSocket c, int code, String r, boolean remote) {}
public void onError(org.java_websocket.WebSocket c, Exception e) {}
};
server.setConnectionLostTimeout(1); // server pings every client each second
server.start();
started.await();
CompletableFuture<Integer> closeCode = new CompletableFuture<>();
WebSocket.Listener listener = new WebSocket.Listener() {
public CompletionStage<?> onPing(WebSocket ws, ByteBuffer message) {
// the JDK replies with a pong automatically
System.out.println("ping from server");
ws.request(1);
return null;
}
public CompletionStage<?> onPong(WebSocket ws, ByteBuffer message) {
long sentAt = message.getLong();
System.out.printf("pong, round trip %.2f ms%n", (System.nanoTime() - sentAt) / 1e6);
ws.request(1);
return null;
}
public CompletionStage<?> onClose(WebSocket ws, int statusCode, String reason) {
System.out.println("onClose: " + statusCode + " " + reason);
closeCode.complete(statusCode);
return null; // the JDK sends the reply close frame for us
}
};
WebSocket ws = HttpClient.newHttpClient().newWebSocketBuilder()
.buildAsync(URI.create("ws://localhost:" + server.getPort()), listener)
.join();
// a ping payload can be up to 125 bytes; here: the send time
ws.sendPing(ByteBuffer.allocate(8).putLong(0, System.nanoTime())).join();
Thread.sleep(2500);
ws.sendText("quit", true).join();
closeCode.join();
server.stop(1000);
}
}
Output:
pong, round trip 6.00 ms
ping from server
ping from server
onClose: 4000 client asked to quit
Closing is a handshake too: one side sends a Close frame with a status code, the other answers with its own Close frame, and then the TCP connection is closed. With the JDK client:
sendClose(code, reason)closes your output. You still receive messages until the server's Close frame arrives inonClose.- When the server closes first,
onCloseis called. Once the stage it returns completes (immediately fornull), the JDK sends the reply Close frame. abort()drops the TCP connection without a handshake. Use it when the peer stops responding.
Common status codes:
| Code | Meaning |
|---|---|
| 1000 | Normal close (WebSocket.NORMAL_CLOSURE) |
| 1001 | Going away: server shutting down or browser leaving the page. server.stop() sends it |
| 1002 | Protocol error |
| 1003 | Unsupported data, e.g. binary sent to a text-only endpoint |
| 1006 | Connection dropped without a Close frame. Never sent, only reported |
| 1008 | Policy violation |
| 1009 | Message too big |
| 1011 | Unexpected server error |
| 4000-4999 | Free for application use |
A chat server with broadcast
A chat server keeps a set of connections and sends every message to all of them. Java-WebSocket tracks open connections for you (getConnections()) and has broadcast(). setAttachment() stores per-connection state, here the user's name:
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class ChatDemo {
static class ChatServer extends WebSocketServer {
final CountDownLatch started = new CountDownLatch(1);
ChatServer(int port) {
super(new InetSocketAddress("localhost", port));
setReuseAddr(true);
}
@Override
public void onStart() { started.countDown(); }
@Override
public void onOpen(org.java_websocket.WebSocket conn, ClientHandshake handshake) {
// the name comes from the URL: ws://host:port/?name=alice
String query = URI.create(handshake.getResourceDescriptor()).getRawQuery();
String name = query != null && query.startsWith("name=")
? URLDecoder.decode(query.substring(5), StandardCharsets.UTF_8)
: "anonymous";
conn.setAttachment(name); // per-connection state
broadcast("* " + name + " joined (" + getConnections().size() + " online)");
}
@Override
public void onMessage(org.java_websocket.WebSocket conn, String message) {
String name = conn.getAttachment();
broadcast(name + ": " + message); // sends to every open connection
}
@Override
public void onClose(org.java_websocket.WebSocket conn, int code, String reason, boolean remote) {
broadcast("* " + conn.getAttachment() + " left");
}
@Override
public void onError(org.java_websocket.WebSocket conn, Exception ex) {
ex.printStackTrace();
}
}
static WebSocket join(HttpClient client, int port, String name) {
WebSocket.Listener printer = new WebSocket.Listener() {
public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
System.out.println("[" + name + "'s screen] " + data);
ws.request(1);
return null;
}
};
return client.newWebSocketBuilder()
.buildAsync(URI.create("ws://localhost:" + port + "/?name=" + name), printer)
.join();
}
public static void main(String[] args) throws Exception {
ChatServer server = new ChatServer(0);
server.start();
server.started.await();
HttpClient client = HttpClient.newHttpClient();
WebSocket alice = join(client, server.getPort(), "alice");
Thread.sleep(200);
WebSocket bob = join(client, server.getPort(), "bob");
Thread.sleep(200);
alice.sendText("hi bob", true).join();
Thread.sleep(200);
bob.sendText("hello alice", true).join();
Thread.sleep(200);
bob.sendClose(WebSocket.NORMAL_CLOSURE, "").join();
Thread.sleep(200);
alice.sendClose(WebSocket.NORMAL_CLOSURE, "").join();
server.stop(1000);
}
}
Output (lines for different clients can appear in a different order):
[alice's screen] * alice joined (1 online)
[alice's screen] * bob joined (2 online)
[bob's screen] * bob joined (2 online)
[bob's screen] alice: hi bob
[alice's screen] alice: hi bob
[alice's screen] bob: hello alice
[bob's screen] bob: hello alice
[alice's screen] * bob left
Real chat messages are usually JSON, e.g. {"type":"message","room":"42","text":"hi"}, parsed with Jackson or Gson on both sides. A type field lets one connection carry several kinds of messages.
To try the server from a browser, start it on a fixed port (new ChatServer(8080)) and type this into the developer console of any page:
const ws = new WebSocket("ws://localhost:8080/?name=carol");
ws.onmessage = e => console.log(e.data);
ws.onopen = () => ws.send("hi from the browser");
Reconnecting
Network connections break: Wi-Fi switches, servers restart, laptops sleep. The JDK client doesn't reconnect by itself. A typical client retries with exponential backoff plus some randomness (jitter), so that thousands of clients don't all reconnect at the same moment after a server restart:
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ThreadLocalRandom;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class Reconnect {
static WebSocket connectWithRetry(HttpClient client, URI uri, WebSocket.Listener listener)
throws InterruptedException {
long delayMs = 250;
for (int attempt = 1; ; attempt++) {
try {
return client.newWebSocketBuilder()
.connectTimeout(Duration.ofSeconds(2))
.buildAsync(uri, listener)
.join();
} catch (Exception e) {
// jitter: sleep between half and all of the current delay
long sleep = ThreadLocalRandom.current().nextLong(delayMs / 2, delayMs + 1);
System.out.printf("attempt %d failed (%s), retrying in %d ms%n",
attempt, e.getCause().getClass().getSimpleName(), sleep);
Thread.sleep(sleep);
delayMs = Math.min(delayMs * 2, 10_000);
}
}
}
public static void main(String[] args) throws Exception {
int port;
try (ServerSocket s = new ServerSocket(0)) { port = s.getLocalPort(); } // a free port
// start the server only after 2 seconds
WebSocketServer server = new WebSocketServer(new InetSocketAddress("localhost", port)) {
public void onStart() { System.out.println("server started"); }
public void onOpen(org.java_websocket.WebSocket c, ClientHandshake h) { c.send("hello"); }
public void onMessage(org.java_websocket.WebSocket c, String msg) {}
public void onClose(org.java_websocket.WebSocket c, int code, String r, boolean remote) {}
public void onError(org.java_websocket.WebSocket c, Exception e) {}
};
Thread.ofVirtual().start(() -> {
try { Thread.sleep(2000); } catch (InterruptedException e) { return; }
server.start();
});
CompletableFuture<String> greeting = new CompletableFuture<>();
WebSocket ws = connectWithRetry(HttpClient.newHttpClient(),
URI.create("ws://localhost:" + port), new WebSocket.Listener() {
public CompletionStage<?> onText(WebSocket w, CharSequence data, boolean last) {
greeting.complete(data.toString());
return null;
}
});
System.out.println("connected, got: " + greeting.join());
ws.sendClose(WebSocket.NORMAL_CLOSURE, "").join();
server.stop(1000);
}
}
Output (delays are random):
attempt 1 failed (ConnectException), retrying in 196 ms
attempt 2 failed (ConnectException), retrying in 294 ms
attempt 3 failed (ConnectException), retrying in 672 ms
attempt 4 failed (ConnectException), retrying in 1889 ms
server started
connected, got: hello
In a long-running client, call the same method when onClose reports a code other than 1000 or when onError is called. Do it on another thread, not inside the listener callback. After reconnecting, the client must resubscribe or resend whatever the server needs, because a new connection starts with no state.
Summary
- A WebSocket starts as an HTTP
GETwithUpgrade: websocket, answered by101 Switching Protocols. After that both sides send text or binary messages whenever they want. - On the client, use the JDK's
HttpClient.newWebSocketBuilder(). On the server, use a library: Java-WebSocket for a small standalone server, Jakarta WebSocket or Spring inside an existing web server. - In a
WebSocket.Listener, callrequest(1)after each message, and collect parts untillastistrue. - The JDK client allows one pending send at a time. Chain sends through a single serializing sender when several threads write.
- Put auth in the handshake (header, cookie or query parameter) and reject bad requests before the connection opens. Agree on a message format with subprotocols.
- Pings keep idle connections alive. Close with a status code, and treat 1006 as a dropped connection.
- Use
wss://in production, and reconnect with exponential backoff and jitter.