Websockets

Undertow provides support for Websockets out of the box. Undertow provides a XNIO based API, which uses the Xnio Channel interface to provide access to the web socket at a low level.

Most users will want a higher level interface than this, and to that end Undertow also provides a Jakarta WebSocket (formerly JSR-356) implementation. As of Undertow 2.4 this implementation is provided by the separate Undertow EE project (groupId io.undertow.ee), in the undertow-websockets artifact (formerly undertow-websockets-jsr under io.undertow). To use it you must make sure that you have the undertow-servlet and undertow-websockets artifacts on your class path. Servlet support is required because the Jakarta WebSocket API is based on the Servlet API.

For maven users the following snippet should be added to your pom.xml:

<dependency>
  <groupId>io.undertow.ee</groupId>
  <artifactId>undertow-servlet</artifactId>
  <version>${version.io.undertow.ee}</version>
</dependency>

<dependency>
  <groupId>io.undertow.ee</groupId>
  <artifactId>undertow-websockets</artifactId>
  <version>${version.io.undertow.ee}</version>
</dependency>

The Core Websocket API

The core API is provided by undertow-core and does not require the Servlet or Jakarta WebSocket artifacts. A websocket endpoint is created using the io.undertow.Handlers.websocket(WebSocketConnectionCallback) factory method, which returns a WebSocketProtocolHandshakeHandler. The handler performs the websocket handshake and then invokes the supplied io.undertow.websockets.WebSocketConnectionCallback once a connection has been established.

The callback is given a WebSocketChannel. To receive messages you register a receive listener on the channel and then call resumeReceives(). The io.undertow.websockets.core.AbstractReceiveListener class provides a convenient base class that assembles complete messages for you (via onFullTextMessage / onFullBinaryMessage). Messages are sent using the static methods of io.undertow.websockets.core.WebSockets.

The following example echoes back any text message that it receives:

import io.undertow.Undertow;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.core.AbstractReceiveListener;
import io.undertow.websockets.core.BufferedTextMessage;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.core.WebSockets;
import io.undertow.websockets.spi.WebSocketHttpExchange;

import static io.undertow.Handlers.path;
import static io.undertow.Handlers.websocket;

Undertow server = Undertow.builder()
        .addHttpListener(8080, "localhost")
        .setHandler(path()
                .addPrefixPath("/myapp", websocket(new WebSocketConnectionCallback() {

                    @Override
                    public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
                        channel.getReceiveSetter().set(new AbstractReceiveListener() {

                            @Override
                            protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
                                WebSockets.sendText(message.getData(), channel, null);
                            }
                        });
                        channel.resumeReceives();
                    }
                })))
        .build();
server.start();

The Jakarta WebSocket (JSR-356) API

Most users will want to use the standard Jakarta WebSocket API (formerly 'Java API for WebSocket', JSR-356) rather than the low level core API. This implementation lives in the io.undertow.ee:undertow-websockets artifact and is built on top of Undertow’s Servlet support, so both undertow-servlet and undertow-websockets (both under io.undertow.ee) must be on the class path.

Jakarta WebSocket endpoints can be defined either by annotating a class with jakarta.websocket.server.ServerEndpoint, or programmatically by providing a jakarta.websocket.server.ServerEndpointConfig. An annotated endpoint looks like this:

import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;

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

    @OnMessage
    public void message(String message, Session session) throws IOException {
        for (Session s : session.getOpenSessions()) {
            s.getBasicRemote().sendText(message);
        }
    }
}

Endpoints are registered with a io.undertow.websockets.jsr.WebSocketDeploymentInfo, which is attached to the Servlet DeploymentInfo as a servlet context attribute under WebSocketDeploymentInfo.ATTRIBUTE_NAME. Annotated endpoints are added with addEndpoint(Class) and programmatic endpoints with addEndpoint(ServerEndpointConfig). A buffer pool must also be supplied via setBuffers(ByteBufferPool):

import io.undertow.server.DefaultByteBufferPool;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;

final ServletContainer container = ServletContainer.Factory.newInstance();

DeploymentInfo deployment = new DeploymentInfo()
        .setClassLoader(ChatEndpoint.class.getClassLoader())
        .setContextPath("/")
        .setDeploymentName("chat.war")
        .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                new WebSocketDeploymentInfo()
                        .setBuffers(new DefaultByteBufferPool(true, 100))
                        .addEndpoint(ChatEndpoint.class));

DeploymentManager manager = container.addDeployment(deployment);
manager.deploy();

// manager.start() returns the HttpHandler for this deployment, which can be
// registered with a PathHandler and set as the root handler of the server.