Return to site

🔌🕸️ JAKARTA EE WEBSOCKET: REAL-TIME SERVER + JAVA CLIENT (NO MAGIC, JUST API)

· jakartaee

🔸 TLDR

▪️ Jakarta WebSocket = standard API (jakarta.websocket) to build real-time apps with annotated server endpoints + Java clients 🚀

Section image

🔸 WHY WEBSOCKETS?

▪️ HTTP is request/response ➡️ WebSocket is full-duplex (both sides can push) ⚡

▪️ Great for live dashboards, chat, collaboration, notifications, streaming telemetry 📈

🔸 DEVELOPING AN ANNOTATED WEBSOCKET SERVER ENDPOINT

▪️ The “classic” Jakarta EE style: a POJO + annotations ✅

▪️ You declare the URL with @ServerEndpoint("/ws/chat") and hook lifecycle events.

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import java.io.IOException;

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

  @OnOpen
  public void onOpen(Session session) {
    System.out.println("🟢 Connected: " + session.getId());
  }

  @OnMessage
  public void onMessage(String msg, Session session) throws IOException {
    // echo back (replace with your domain logic 😉)
    session.getBasicRemote().sendText("👋 " + msg);
  }

  @OnClose
  public void onClose(Session session, CloseReason reason) {
    System.out.println("🔴 Closed: " + session.getId() + " (" + reason + ")");
  }

  @OnError
  public void onError(Session session, Throwable err) {
    System.out.println("💥 Error on " + (session != null ? session.getId() : "?") + ": " + err);
  }
}

▪️ Tip: use session.getAsyncRemote() when you don’t want to block IO threads 🧵

▪️ Tip: you can use path params like /ws/chat/{room} to route users to rooms 🏷️

🔸 DEVELOPING WEBSOCKET CLIENTS IN JAVA

▪️ Jakarta WebSocket also provides a client API (yes, not only server) 🧑💻

▪️ You can connect with WebSocketContainer (portable across implementations).

import jakarta.websocket.*;
import java.net.URI;

@ClientEndpoint
public class MyClient {

  @OnOpen
  public void onOpen(Session session) {
    System.out.println("✅ Client connected");
    session.getAsyncRemote().sendText("Hello from client!");
  }

  @OnMessage
  public void onMessage(String msg) {
    System.out.println("📩 Received: " + msg);
  }

  public static void main(String[] args) throws Exception {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    container.connectToServer(MyClient.class, URI.create("ws://localhost:8080/ws/chat"));
  }
}

▪️ If you need custom headers, timeouts, subprotocols, or encoders/decoders, use ClientEndpointConfig + message handlers 🎛️

🔸 TYRUS: EXTRA GOODIES (REFERENCE IMPLEMENTATION VIBES)

▪️ Eclipse Tyrus is the well-known implementation around the WebSocket API ecosystem and comes with practical tooling & examples 📚

▪️ Handy topics in the Tyrus guide:

▪️ Deploy endpoints as WAR or via ServerContainer (programmatic deployment) 🧩

▪️ Deep dive into endpoints / sessions / message handlers (great to understand what really happens) 🔍

▪️ Proprietary config (advanced client tuning like masking key generator) ⚙️

🔸 TAKEAWAYS

▪️ Start with @ServerEndpoint + @OnMessage for a clean, readable entry point ✨

▪️ Use AsyncRemote when scaling broadcasts or frequent pushes ⚡

▪️ The client API is first-class: don’t default to JS clients only 🧑💻

▪️ When debugging, think in Session + MessageHandlers + lifecycle (open/message/close/error) 🧠

▪️ Need more than “hello world”? The Tyrus user guide is a goldmine 📘: https://eclipse-ee4j.github.io/tyrus-project.github.io/documentation/latest/index/

#JakartaEE #WebSocket #Java #EclipseTyrus #RealTime #Backend #Microservices #DistributedSystems #APIs #DeveloperTips

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaBook👇