Java WebSocket Basics

Su Suriya Ravichandran Updated 18 Nov 2026
17 min read ·Lesson 210 of 306

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.

StepWhat travels over the connection
1. Handshake requestGET /chat HTTP/1.1 with Upgrade: websocket and a random Sec-WebSocket-Key
2. Handshake responseHTTP/1.1 101 Switching Protocols with a matching Sec-WebSocket-Accept
3. MessagesText or binary frames, in either direction, at any time
4. Keep-alivePing frames, answered with pong frames
5. ClosingEach side sends a close frame with a status code
HTTP request/responseWebSocket
Who starts a messageAlways the clientClient or server
ConnectionUsually short, one exchangeStays open for many messages
Overhead per messageFull set of headers2 to 14 bytes of frame header
URI schemehttp://, 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.

TypeRole
WebSocket.BuilderFrom httpClient.newWebSocketBuilder(); sets headers, subprotocols and the connect timeout
WebSocketThe open connection; you call it to send
WebSocket.ListenerYour callback object; the client calls it when something is received
WebSocket methodPurpose
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 a CompletableFuture<WebSocket>. join() waits until the connection is open.
  • onOpen() runs once the connection is ready. Calling webSocket.request(1) there tells the client "I am ready for one message".
  • Each received text message calls onText(). The listener copies it into a LinkedBlockingQueue, and the main thread takes it out with poll(2, SECONDS), which waits up to 2 seconds.
  • sendText("Hello WebSocket!", true) sends a whole message (last is true). The server broadcasts it back as Meena: Hello WebSocket!.
  • sendClose(NORMAL_CLOSURE, "bye") sends close code 1000 and 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 methodCalled 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 an Authorization token.
  • .subprotocols("chat.v1") offers a subprotocol. The server accepted it, so getSubprotocol() returns chat.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 in onPong(). 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 status 1000 and the reason, and the program waits for it with the closed future.
  • Both isInputClosed() and isOutputClosed() are true once the closing handshake is complete.
Common close codeConstant / meaning
1000WebSocket.NORMAL_CLOSURE: finished normally
1001Going away (server shutting down, page closed)
1008Policy violation (for example, not allowed)
1011Unexpected 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 passes true. 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.
  • WholeMessageListener appends every part to a StringBuilder and publishes the message only when last is true. That is why the 5,000-character message (plus the Kavya: prefix, 5,007 characters) arrives whole, however the client splits it internally.
  • The data passed to onText() must be copied before the method returns, because the client may reuse it.

Note: Never assume one onText() call equals one message. Always check last, 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().

CauseMeaning
WebSocketHandshakeExceptionThe server answered, but not with 101 Switching Protocols; getResponse() gives the HTTP response
ConnectExceptionNothing listens on that host and port
HttpTimeoutExceptionThe connect timeout expired
IllegalArgumentExceptionThe 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.
  • /news is not a WebSocket endpoint: the server answers 404, and WebSocketHandshakeException.getResponse().statusCode() reveals it.
  • Port 8097 has no server, so the cause is ConnectException.
  • An http:// URI is rejected because WebSockets require ws:// or wss://.
  • 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() and messages() 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:

  1. Hidden listener. The private inner Listener class handles events and writes complete messages to the inbox queue. Callers only see say(), nextMessage() and messages().
  2. 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.
  3. Waiting with deadlines. messages(count, timeout) collects up to count messages 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.
  4. 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.
  5. Clean closing. close() sends a close frame, then waits up to 2 seconds for onClose() to complete closeStatus. If the server never answers, abort() drops the connection so the program cannot hang.
  6. Nested lifetimes. Try-with-resources closes Vikram's client first and then Asha's, and the HttpClient is 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java WebSocket Basics and get answers drawn from it.

Signed-in readers only.