In this post, let’s explore the less talked about Web Socket Client API and how to leverage it within a Java EE 7 container itself
Web Socket Server API rules
What about the Web Socket client side API ?
The Web Socket specification includes a client side API as well and its mandatory for all JSR 356 (e.g. Tyrus, Undertow etc) implementations to provide one. There are quite a few use cases wherein a browser based / end user facing web socket client might not be required.
Consider a scenario where you want to connect to a third party Web Socket end point, consume it’s information and persist it for later use ? Maybe for further analysis ? In such cases, its useful to leverage the client API within the Java EE container itself.
Let’s explore this with a simple example.
(annotated) Web Socket Client
Note: the logic for @OnMessage was excluded on purpose and has been implemented in a different way (clarified later)
A Stock Ticker (info) JPA entity
A Stateless bean
- Handles persistence of Stock Ticker info
- Executes its operations against the default JDBC data source provided by the Java EE 7 container (convention over configuration in action!)
- Leverages the Web Socket ContainerProvider API
- Initiates the connection to a web socket server
- Injects the StockInfoPersistenceService bean and uses it within the addMessageHandler implementation
As per previous note, the (persistence) logic which could have been embedded in a @OnMessage annotated method within the StockTickerClient class has been included here. This is because the injection of the StockInfoPersistenceService (stateless) bean was failing and the instance itself was being resolved to null.
That’s pretty much it. Although this was a relatively simple example, its not too hard to imagine that one can apply any sort of complex business logic on the information received by the web socket server endpoint. You might also want to think about sending messages to connected clients in an asynchronous fashion using the session.getAsyncRemote#sendAsync method
Also check out …
… a new eBook – Java WebSocket API Handbook