14.3.1. WebSocket endpoints
WebSockets have two types of endpoints: programmatic and annotated.
Programmatic endpoints split the responsibilities of handling the connection lifecycle
events and message processing into separate classes. With a programmatic endpoint, you're
responsible for extending javax.websocket.Endpoint to handle the initial con-
nection request. There are also callbacks for handling errors, as well as connection close
events. When a connection is opened, you can register javax.websocket .Mes-
sageHandler instances to process incoming messages.
Although programmatic endpoints are more complicated to construct than annotated end-
points, they're more versatile from an architectural perspective. Message handlers can be
reused by multiple endpoints and thus aren't tied to a specific URI.
Annotated endpoints, as their name implies, use annotations to define and configure a We-
bSocket endpoint. An annotated endpoint can be any Java class; unlike programmatic en-
dpoints, there's no class or interface from which you must inherit. There's no difference
in message-handling capabilities, so the decision on whether to use programmatic or an-
notated endpoints depends solely on architectural considerations. With annotated endpoints
you mark both lifecycle and messaging-handling methods with annotations.
Using WebSockets with EJB
There are two types of integration between WebSockets and EJBs to consider: exposing an
EJB as a WebSocket endpoint and invoking an EJB from a WebSocket endpoint. The first
approach isn't well defined in the Java EE 7 specification. Although a WebSocket endpoint
could conceptually be a stateful session bean or a singleton bean, there's no explicit support
for either case. Some containers, such as GlassFish 4.0 that uses the Tyrus WebSocket im-
plementation, support exposing a singleton bean as a WebSocket endpoint, but this support
isn't standardized yet. Your mileage may vary with other containers.
The second approach is supported. Using the @EJB annotation, you can inject references
to EJBs into a WebSocket endpoint or message handler. This approach is better from an