TCP Client using Eclipse Vert.x, Kotlin and Gradle build

As part of my hobby project to con­trol Rasp­ber­ryPi using Google Home Mini and/or Alexa, I wanted to write a very sim­ple TCP client that keeps a con­nec­tion open to one of my cus­tom writ­ten server in cloud (I will write an­other blog post to cover the server side on a later date). The re­quire­ment of the client is to send a shared se­cret upon con­nect­ing and then keep wait­ing for mes­sage from server. Vert.x, Kotlin and Gra­dle allow rapid de­vel­op­ment of such project. The gen­er­ated jar can be ex­e­cuted on Rasp­berry Pi. These steps out­line the project setup and re­lated source code to show­case a Vert.x and Kotlin project with Gra­dle.

Project Directory Structure

From com­mand line (or via Win­dows Ex­plorer, what­ever you pre­fer to use) cre­ate a di­rec­tory for project,for in­stance vertx-net-client. Since we are using Kotlin, we will place all Kotlin files in src/main/kotlin folder. The src/main/resources folder will con­tain our log­ging con­fig­u­ra­tion re­lated files.

cd vertx-net-client
mkdir -p src/main/kotlin
mkdir -p src/main/resources

Project Files

We need to add fol­low­ing files in the project

  • .gitignore If you want to check your project into git, you may con­sider adding fol­low­ing .gitignore file at root of your project
...waiting for Gist...
  • logback.xml This ex­am­ple is using slf4j and log­back for log­ging. If you de­cide to use it in your project, you may also add fol­low­ing log­back.xml file in src/main/resources. Mod­ify it as per your re­quire­ments. This ex­am­ple will log on con­sole.
...waiting for Gist...

Gradle Setup

We will use Gra­dle build sys­tem for this project. If you don’t al­ready have Gra­dle avail­able on your sys­tem, down­load and unzip gra­dle in a di­rec­tory of your choice ($GRADLE_HOME is used here to rep­re­sent this di­rec­tory). This gra­dle dis­tri­b­u­tion will be used as a start­ing point to cre­ate Gra­dle wrap­per scripts for our project. These scripts will allow our project to down­load and use cor­rect ver­sion of gra­dle dis­tri­b­u­tion au­to­mat­i­cally with­out mess­ing up sys­tem. Re­ally use­ful when build­ing your project on CI tool or on any other de­vel­oper’s ma­chine.

Run fol­low­ing com­mand in project’s di­rec­tory

$GRADLE_HOME/bin/gradle wrapper

The above com­mands will gen­er­ate fol­low­ing files and di­rec­to­ries.

gradle/  gradlew  gradlew.bat

Gradle build file build.gradle

Cre­ate (and/or copy and mod­ify) fol­low­ing build.gradle in your project’s root di­rec­tory. Our ex­am­ple gra­dle build file is using vertx-​gradle-plugin.

...waiting for Gist...

In the project di­rec­tory, run fol­low­ing com­mand to down­load local gra­dle dis­tri­b­u­tion:

./gradlew

(or .\gradlew.bat if in Win­dows)

At this stage we should have fol­low­ing file struc­ture. This is also a good time to com­mit changes if you are work­ing with git.

  • .gitignore
  • build.gradle
  • gradle/wrapper/gradle-wrapper.jar
  • gradle/wrapper/gradle-wrapper.properties
  • gradlew
  • gradlew.bat
  • src/main/resources/logback.xml

Now that our project struc­ture is ready, time to add the meat of the project. You may use any IDE of your choice. My pref­er­ence is In­tel­liJ IDEA.

Cre­ate a new pack­age under src/main/kotlin. The pack­age name should be adapted from the fol­low­ing sec­tion of build.gradle

vertx {
    mainVerticle = "info.usmans.blog.vertx.NetClientVerticle"
}

From the above ex­am­ple, the pack­age name is info.usmans.blog.vertx

Add a new Kotlin Class/file in src/main/kotlin/info/usmans/blog/vertx as NetClientVerticle.kt

The con­tents of this class is as fol­lows

...waiting for Gist...

Explaining the Code

The fun main(args: Array<String>) is not strictly re­quired, it quickly al­lows run­ning the Vert.x ver­ti­cle from within IDE. You will also no­tice a small hack in the method for set­ting sys­tem prop­erty vertx.disableDnsResolver which is to avoid a Netty bug that I ob­served when run­ning on Win­dows ma­chine and re­mote server is down. Of course, since we are using vertx-​gradle-plugin, we can also use gradle vertxRun to run our ver­ti­cle. In this case the main method will not get called.

The override fun start() method calls fireReconnectTimer which in turn calls reconnect method. reconnect method con­tains the con­nec­tion logic to server as well as it calls fireReconnectTimer if it is un­able to con­nect to server or dis­con­nects from server. In reconnect method the socket.handler gets called when server send mes­sage to client.

socket.handler({ data ->
                        logger.info("Data received: ${data}")
                        //TODO: Do the work here ...
               })

Distributing the project

To cre­ate re­dis­trib­utable jar, use ./gradlew shadowJar com­mand. Or if using In­tel­liJ: from Gra­dle projects, Tasks, shadow, shad­ow­Jar (right click run). This com­mand will gen­er­ate ./build/libs/vertx-net-client-fat.jar.

Executing the client

The client jar can be ex­e­cuted using fol­low­ing com­mand:

 java -DserverHost=127.0.0.1 -DserverPort=8888 -DconnectMessage="hello" -jar vertx-net-client-full.jar

If you wish to use SLF4J for Vert.x in­ter­nal log­ging, you need to pass sys­tem prop­erty vertx.logger-delegate-factory-class-name with value of io.vertx.core.logging.SLF4JLogDelegateFactory. The final com­mand would look like:

java -DserverHost=127.0.0.1 -DserverPort=8888 -DconnectMessage="hello" -Dvertx.logger-delegate-factory-class-name="io.vertx.core.logging.SLF4JLogDelegateFactory" -jar vertx-net-client-full.jar

You can con­fig­ure Vert.x log­ging lev­els in log­back.xml file if re­quired.

Conclusion

This post de­scribes how easy it is to cre­ate a sim­ple TCP client using Vert.x, Kotlin and Gra­dle build sys­tem. Hope­fully the tech­niques shown here will serve as a start­ing point for your next DIY project.

This post is adapted and re­pro­duced from au­thor’s blog post

Next post

Eclipse Vert.x based Framework URL Shortener Backend

We combine Vert.x with the serverless framework to write a microservice that runs on AWS Lambda.

Read more
Previous post

Eclipse Vert.x meets GraphQL

In this blog post, we will look at an example application written in Vert.x that uses the new GraphQL API of Gentics Mesh.

Read more
Related posts

Centralized logging for Vert.x applications using the ELK stack

This post entry describes a solution to achieve centralized logging of Vert.x applications using the ELK stack (Logstash, Elasticsearch, and Kibana).

Read more

Using the asynchronous SQL client

Finally, back... This post is the fifth post of the introduction to vert.x blog series, after a not-that-small break. In this post we are going to see how we can use JDBC in a vert.x application.

Read more

Some Rest with Vert.x

This post is part of the Introduction to Vert.x series. Let’s go a bit further this time and develop a CRUD-ish application

Read more