This is a short guide on how to use an embedded Undertow webserver coupled with Guice for IoC, to expose a WebSocket endpoint. You can check out a sample project’s source code on github.
A custom ClassIntrospector is used to construct a ServerEndpoint instance that expects a dependency to be injected through it’s @Inject annotated constructor.
A Basic WebSocket Deployment
Exposing a WebSocket endpoint with JSR 356 became as easy as:
The following class exposes the endpoint using an embedded Undertow server.
The WebSocketEndpoint class requires a SessionHolder instance that keeps track of all connected users. The SessionHolder’s construction and injection should be handled by Guice.
Since a class marked with the ServerEndpoint annotation is expected to have a 0-ary constructor, the WebSocket deployment will fail at runtime throwing a javax.websocket.DeploymentException. A custom ClassIntrospector can be used to provide an Instance Factory which is aware of Guice and can properly handle object construction.