Understanding Vert.x: working with WebSockets

Alexey Soshin
2 min readFeb 10, 2019

--

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 WebSocksServerVerticle:

It’s usually good idea to wrap most of your Vert.x code in Verticles. Also, try not to write business logic inside start() 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 start() method:

Our client connects to localhost:8080, 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: exceptionHandler will be triggered when something crashes violently, and closeHandler will be triggered on graceful events.

Finally, let’s see what restart() looks like:

As you can see, not putting everything into start() 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 IOException or something else?) and in case of gracefully closed connections — the response code.

--

--

Alexey Soshin

Solutions Architect @Depop, author of “Kotlin Design Patterns and Best Practices” book and “Pragmatic System Design” course