Introduction: Why WebSocket Became the Standard for Real-Time Communications
Modern web applications require instant reaction to events. Whether it's a chat, a trading terminal, or a multiplayer game — users expect data to update without reloading the page. Traditional HTTP (REST API) with its "request-response" model is inefficient for such tasks: the client is forced to constantly poll the server, which creates unnecessary load and delays.
The solution to this problem is the WebSocket protocol, which establishes a permanent two-way connection between the client and server. In this article, we will break down WebSocket in Java from the basics to creating a full-fledged real-time application. You will learn how to set up a server, write a client, and handle errors.
WebSocket Basics: How It Works
Difference from HTTP
WebSocket is a protocol that works over TCP. It starts as an HTTP request (handshake), after which the connection "upgrades" to a permanent two-way channel. Unlike HTTP, where each request requires a new connection, WebSocket keeps it open, allowing the server to send data to the client independently (push model).
Main advantages:
- Low latency — data is transmitted instantly without repeated handshakes.
- Less traffic — minimal header (only 2-14 bytes) versus hundreds of bytes in HTTP.
- Bidirectionality — both the client and server can initiate data sending.
Architecture of a Real-Time Application in Java
A typical application consists of three components:
- Client (browser or mobile application) that initiates the connection.
- Application server (Java) that manages WebSocket sessions.
- Backend (database, message queues) that handles business logic.
Java provides powerful tools for working with WebSocket — both on the server side (Jakarta WebSocket, Spring WebSocket) and on the client side (standard Java WebSocket API).
Creating a WebSocket Server in Java
Environment Setup
For the server side, we will use Jakarta WebSocket (formerly Java EE WebSocket). This is a standard API that is part of Jakarta EE. You will need:
- JDK 11 or higher.
- An application server (e.g., Apache Tomcat 10 or GlassFish 7).
- Maven for dependency management.
Add the dependency to pom.xml:
<dependency> <groupId>jakarta.websocket</groupId> <artifactId>jakarta.websocket-api</artifactId> <version>2.1.0</version> <scope>provided</scope></dependency>Writing a WebSocket Endpoint
Let's create a simple echo server that sends back the received message:
import jakarta.websocket.*;import jakarta.websocket.server.ServerEndpoint;
@ServerEndpoint("/chat")public class ChatEndpoint {
@OnOpen public void onOpen(Session session) { System.out.println("New connection: " + session.getId()); }
@OnMessage public String onMessage(String message, Session session) { System.out.println("Received from " + session.getId() + ": " + message); return "Echo: " + message; }
@OnClose public void onClose(Session session, CloseReason reason) { System.out.println("Connection closed: " + session.getId() + " due to: " + reason.getReasonPhrase()); }
@OnError public void onError(Session session, Throwable error) { System.err.println("Error in session " + session.getId() + ": " + error.getMessage()); }}The annotation @ServerEndpoint("/chat")
Blogs
Book Recommendations
Read also
PHP Libraries That Will Save Your Project: A 2024 Ecosystem Guide
Internationalization of TypeScript Applications: A Complete Guide with Examples
Creating Your Own Programming Language: DSL in JavaScript
Full URL in PHP: How to Get It Quickly and Without Errors
Sorting an Array of Objects in PHP: By One Property for Beginners