WebSocket in Java: Building Real-Time Applications

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why WebSocket is the Standard for Real-Time Applications in Java

Modern web applications require instant data exchange between client and server. The traditional HTTP protocol, based on the "request-response" model, is poorly suited for tasks where minimal latency is critical: online chats, stock quotes, multiplayer games, or real-time monitoring dashboards.

The WebSocket protocol solves this problem by establishing a persistent bidirectional connection between client and server. After the initial HTTP handshake, the connection is "upgraded" to WebSocket, and data is transmitted in the form of frames without additional headers. Java, thanks to its powerful standard library and frameworks, provides excellent tools for working with WebSocket.

In this article, we will look at how to create a full-fledged real-time application in Java using the Jakarta WebSocket API (formerly Java EE WebSocket). You will learn about server configuration, message handling, session management, and typical architectural solutions.



WebSocket Basics in Java: Jakarta WebSocket API

Starting with Java EE 7 (Jakarta EE), JSR 356 — the Java API for WebSocket — was added to the standard platform. This means that to create a WebSocket server, you don't need to include third-party libraries — just a servlet container that supports Jakarta EE (e.g., Apache Tomcat 9+, Jetty 10+, WildFly).



Creating a WebSocket Endpoint

The main element is an endpoint class annotated with @ServerEndpoint. Inside it, we define methods that will be called upon connection, message receipt, error, or connection closure.



import jakarta.websocket.*;import jakarta.websocket.server.ServerEndpoint;import java.io.IOException;import java.util.Set;import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/chat")public class ChatEndpoint {

private static final Set<Session> sessions = new CopyOnWriteArraySet<>();

@OnOpen public void onOpen(Session session) { sessions.add(session); broadcast("User connected. Total: " + sessions.size()); }

@OnMessage public void onMessage(String message, Session session) { broadcast("[" + session.getId() + "]: " + message); }

@OnClose public void onClose(Session session) { sessions.remove(session); broadcast("User disconnected. Remaining: " + sessions.size()); }

@OnError public void onError(Session session, Throwable throwable) { System.err.println("Error in session " + session.getId() + ": " + throwable.getMessage()); }

private void broadcast(String message) { for (Session s : sessions) { if (s.isOpen()) { try { s.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } } } }}


In this example:

  • @ServerEndpoint("/chat") — specifies that the endpoint is available at the relative path /chat.
  • CopyOnWriteArraySet — a thread-safe collection for storing active sessions.
  • @OnOpen — called when a connection is established.
  • @OnMessage — called when a text message is received.
  • @OnClose — called when a connection is closed.
  • @OnError — error handling.


Client-Side JavaScript

For testing the server, a simple HTML file with JavaScript is sufficient:

<!DOCTYPE html><html><head>    <title>WebSocket Chat</title></head><body>    <div id="messages"></div>    <input type="text" i                

Blogs

Book Recommendations