A Websocket Client using the Java 11 WebSocket API

Tarek Elsibay
Coinmonks
3 min readSep 19, 2020

--

For a small crypto project i wanted to use the Bitfinex WebSocket API to get market data in real time. The full code is available on github.

Since Java SE 11 the JDK contains a client WebSocket API. The javadoc contains some code examples but you cannot use these examples out of the box. Searching the net for „java websocket client“ reveals mostly examples and guides for the old JSR 352 websocket stuff. Setting up everything to get things done was not so straightforward as expected, so Iwrote this little tutorial.

Whenever it suits, I use vert.x in my projects, and there is a websocket client API, too. But sadly the vert.x websocket client has a little shortcoming, it does not work with redirects ☹ Although we do not use the vert.x websocket client, we use vert.x as base of our small application.

Enough words, we start coding. To build and connect to a websocket server, the builder needs a listener, which will listen to incoming data packets:

We override the onOpen method to establish a periodic ping to bitfinex. One important thing is, that when you override onOpen you must call super.onOpen, otherwise the client does not send any data to the server.

It costs me a lot of time to find this error. As the Listener is an interface i am not used to call super methods of interfaces. But in this case it’s important. The concept of default methods in interfaces introduced in Java 8 has still not become second nature to me.

The onText message collects all transmitted text data until a text is complete (this is usually the case in one call to inText). On text completion the text is send via the vert.x eventbus in the onMessage method.

Now we can setup a verticle that represents a connection to bitfinex using this listener:

The class is easy and straightforward, in the start method of the verticle a websocket connection to the public bitfinex api isinitialized and started. Via the vert.x eventbus messages should be sent directly to the websocket, therefore we start a consumer on the address BITFINEX_EB_ADDRESS.

At last step we put everything together and try to subscribe to the tBTCUSD ticker:

The main method starts Vertx and deploys the bitfinex websocket verticle. When the deployment is finished, we send a message to the websocket verticle with a subscription payload and start a consumer on a special eventbus address.

You can find all the code on github, clone it, assure that you have Java 11 or higher installed and run it with:

I hope this tutorial will give you a fast startup with your websocket client code in your project.

--

--

Tarek Elsibay
Coinmonks

Enthusiastic java/kotlin backend server developer. Passionate about vert.x, climate change, EVs, green energy. https://github.com/notizwerk