Implement Jakarta WebSocket 2.2 endpoints in Tomcat using @ServerEndpoint and programmatic registration. Configure sessions, message handlers, encoders, decoders, and SSL.
Use this file to discover all available pages before exploring further.
Tomcat implements Jakarta WebSocket 2.2 through its org.apache.tomcat.websocket module. The WsSci (jakarta.servlet.ServletContainerInitializer) automatically registers WebSocket infrastructure on startup — no additional servlet configuration is required. WebSocket endpoints can be created using the @ServerEndpoint annotation or by extending jakarta.websocket.Endpoint programmatically.
For standard WAR deployments to Tomcat, WebSocket support is built in — no additional dependency is needed in your application’s pom.xml. For embedded Tomcat or testing, add:
Use @ServerEndpoint to declare a WebSocket endpoint. Annotate handler methods with @OnOpen, @OnMessage, @OnClose, and @OnError.
ChatEndpoint.java
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); System.out.println("Connection opened: " + session.getId() + " (total: " + sessions.size() + ")"); } @OnMessage public void onMessage(String message, Session sender) throws IOException { // Broadcast to all connected clients for (Session session : sessions) { if (session.isOpen()) { session.getBasicRemote().sendText(sender.getId() + ": " + message); } } } @OnClose public void onClose(Session session, CloseReason reason) { sessions.remove(session); System.out.println("Connection closed: " + reason.getReasonPhrase()); } @OnError public void onError(Session session, Throwable throwable) { sessions.remove(session); throwable.printStackTrace(); }}
Tomcat calls @OnMessage methods serially for the same Session — concurrent delivery to a single session is not possible. However, different sessions can be handled concurrently by different threads.
Encode and decode Java objects to WebSocket messages by implementing Encoder.Text<T> and Decoder.Text<T>:
JsonEncoder.java
import jakarta.websocket.*;import com.fasterxml.jackson.databind.ObjectMapper;public class JsonEncoder implements Encoder.Text<MyMessage> { private static final ObjectMapper mapper = new ObjectMapper(); @Override public String encode(MyMessage object) throws EncodeException { try { return mapper.writeValueAsString(object); } catch (Exception e) { throw new EncodeException(object, "JSON encoding failed", e); } } @Override public void init(EndpointConfig config) {} @Override public void destroy() {}}
Register encoders and decoders on the endpoint:
@ServerEndpoint( value = "/api", encoders = { JsonEncoder.class }, decoders = { JsonDecoder.class })public class ApiEndpoint { @OnMessage public MyMessage handleMessage(MyMessage msg, Session session) { // Return value is automatically encoded and sent to the client return new MyMessage("Received: " + msg.getText()); }}
@OnOpenpublic void onOpen(Session session) { // Idle timeout in milliseconds; 0 = never session.setMaxIdleTimeout(60_000); // Max text message size in bytes session.setMaxTextMessageBufferSize(65536); // Max binary message size in bytes session.setMaxBinaryMessageBufferSize(65536);}
Always set maxIdleTimeout to a reasonable value (e.g., 60,000 ms). Without it, clients that disconnect without sending a Close frame will leave a Session open indefinitely, eventually exhausting server resources.
Server-side wss:// requires no WebSocket-specific configuration. Simply configure an SSL Connector in server.xml as described in the SSL/TLS guide. Tomcat automatically upgrades HTTP/HTTPS connections to ws:///wss:// respectively.
Tomcat supports the permessage-deflate WebSocket extension (RFC 7692) automatically. If the client advertises support, Tomcat negotiates and uses compression transparently. No configuration is required on the server side.
Embedding Tomcat
Add WebSocket endpoints to an embedded Tomcat instance.