Understanding Vert.x: working with WebSockets

Photo by Ivan Cortez on Unsplash

This story was written in continuation to the following StackOverflow question: https://stackoverflow.com/questions/54608064/how-to-implement-websocket-client-reconnect-after-some-time-in-vertx/54617812#54617812

So, you want to write your own websocket server, and decided to do it in Vert.x

Good idea!

Let’s start with creating our :

It’s usually good idea to wrap most of your Vert.x code in Verticles. Also, try not to write business logic inside method.

Extract it into a separate method instead.

WebSocketServer is like HttpServer, but with WebSockets:

Somebody needs to start the conversation. So, on each new connection our websocket server will send a “ping” message.

To make it a bit more interesting, once in a while our server should close the connection. Note that this is a graceful close. We could also emulate different kinds of crashes, but for now closing will be more than enough.

Once we done with the server, let’s move to the client.

Once again, break you code into verticles, don’t put logic into method:

Our client connects to , as was specified by the server.

For each “ping” message we respond with “pong” message. Not very inventive, but gets the job done.

The interesting part here is that we specify two handlers: will be triggered when something crashes violently, and will be triggered on graceful events.

Finally, let’s see what looks like:

As you can see, not putting everything into method allows smart reuse of the logic.

Also, remember to close the previous client before creating a new one.

The deployment is pretty straightforward:

We wait for Server to start before we start our Client.

The output should look something like this:

Server pong
Client ping
Server pong
Client ping
Server pong
Closed, restarting in 10 seconds
Client ping
Server pong
Client ping

Conclusions

Writing either websocket client or server using Vert.x doesn’t take more that 10 lines of code.

Handling connection problems is very important.

You may want to handle both closed connections and exceptions, or only one of those cases. In a real world application it’s also a good idea to check for type of exception you received (is it or something else?) and in case of gracefully closed connections — the response code.

Solutions Architect @Depop, author of “Hands-on Design Patterns with Kotlin” book and “Web Development with Kotlin” course

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store