Example of WebSocket/STOMP using Java

WebSockets enable 2-way, duplex communication between client and server. All major browsers and all major Java servers like Jetty 9, Tomcat 7, etc. support websockets. The present example has been done with Tomcat 8 as a server and a Tyrus based simple Java client.

Simple WebSocket Server

We will use the WebSocket API to create a simple Server.

Configuration: pom.xml

The pom would be the same as a typical JEE pom. Just put the following dependency:

Server Code

Simple WebSocket Java Client

Configuration: pom.xml

The pom would be a simple one, just add these following dependencies:

Client Code

Define an Endpoint:

Then invoke this:

Note that there is a 2-way communication from server/client. This is handled in the MessageHandler defined in SimpleClientEndpoint:

Spring WebSocket Handler Server

Though the above example is simple and good for starters, this is not practical. For one, it does not integrate with Spring. Lets build something more closer to the real world.

Overview

The client attempts to invoke the BankDetailsService asynchronously, through websockets. For this, it first initiates the request, sending the server the sort-order. The server then triggers a dao-call. Each time when a new row is read off the ResultSet, it is immediately sent to the client. After all the records have been read, the session is closed. Note that the messages are binary. Json strings are gzipped and then sent across the wire to save bandwidth.

We will use the Spring websocket module for integrating WebSockets with Spring.

Configuration: pom.xml

We would need the spring websocket module:

Spring Configuration

The ExceptionWebSocketHandlerDecorator is a decorator for handling any runtime exception gracefully by closing the connection.

Server Code

This is how the BankDetailsWebSocketHandler looks like:

Note that the actual action happens in DataListenerForStompHandlerImpl:

This class is passed to the Dao, and after each record is read from the ResultSet, it is sent to the client.

Client Code

Let us take a look at the client. We are still using a standard WebSocket client, not the Spring stomp client.

Like the 1st example, we have defined our Endpoint as below:

All subsequent messages from the server would flow into the MessageHandler defined in the above class. The above is now invoked here:

Source Code

https://github.com/paawak/blog/tree/master/code/stomp

References

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html

https://tyrus.java.net/documentation/1.12/index/getting-started.html

https://www.websocket.org/echo.html

Leave a Reply

Your email address will not be published. Required fields are marked *