Netty Project | Create custom codec to encode decode custom object, file data | Enhanced Chat Application

In earlier article, we went through basic concepts of Netty & a very simple example of Chat application.

Netty Project | Understanding Netty using simple real-world example of Chat server client | Good for beginners



Example in this article

In this article, we will enhance that same chat application & add a custom codec to encode/decode custom object with file read as explained below.

  • Use same chat application from earlier article.
  • Introduce special chat message (or command) which client can enter in format “file:<file-name>”.
  • Create custom POJO object with that command & name of client who ran command. Write that POJO object to channel.
  • Create custom codec which will take the custom POJO object & encode/decode. It will take file name from command, read the content of the file. Then it will create a String with client name, file name, file content & start-end marking of content. Then write this String to server. Decoding will be done as plain text.
  • This way other client will receive the content of the file.

Lets code

Here is the custom POJO object which we will use in client.




Here is the custom codec which will take above custom POJO object & encode it as per above requirements of this example.

Now we will modify Chat client from earlier article to accept special command & based on that command create custom object & write that object to channel.




In order to test, also add below 2 text files at the root of the project.

Rest of the code can remain as it is. Here is the remaining code files.





Executing the enhanced chat application

Steps for execution are same as earlier article. Here are the console logs.

ChatServer console logs

First ChatClient console logs



Second ChatClient console logs

 

You can find complete code in GIT Repository.

 



Leave a Reply

Your email address will not be published.