Netty vs Tomcat explained

This question often arises in forums so let’s discuss here what is the difference between Netty framework and Tomcat Web server.

Netty , is an asynchronous event-driven network application framework. It enables quick and easy development of network applications such as protocol servers and client.

Tomcat (or any other Web server such as Undertow or Jetty) is a Web Server that manages HTTP request/responses and implements a set of standards such as the Java Servlet API.

In general terms, you can use Netty to make the implementation of custom network protocols relatively easy. To do that, you can extend a SimpleChannelInboundHandler using as data a io.netty.handler.codec.http.HttpObject:

public class HttpHelloWorldServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
       // implement flush
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
       // read HTTP Request
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
      // Handle Exception
    }
}

As you can see, it’s fairly easy to use Netty as a basic HTTP Server. On the other hand, it would require a lot of work to implement all the features available in a Web server such as Tomcat or Undertow.

To see a full example of Netty HTTP Server, check this article: How to create an HTTP Server with Netty

To show a comparison, you can embed Tomcat Web server in your application with little effort:

Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
 
// configure the server
// configure web applications
 
tomcat.start();

In summary:

  • Use Tomcat to handle standard Java Container use cases, such as Servlets, JSP or framework which are built upon this stack
  • Use Netty If you deal a lot with network protocols and want it to be non-blocking use Netty usually for high-performance cases.