Convert Figma logo to code with AI

netty logonetty

Netty project - an event-driven asynchronous network application framework

33,371
15,906
33,371
598

Top Related Projects

TCP/HTTP/UDP/QUIC client/server with Reactor over Netty

High performance non-blocking webserver

14,281

Vert.x is a tool-kit for building reactive applications on the JVM

Asynchronous Http and WebSocket Client library for Java

11,358

The Java gRPC implementation. HTTP/2 based RPC

Quick Overview

Netty is an asynchronous event-driven network application framework for rapid development of maintainable high-performance protocol servers and clients. It simplifies and streamlines network programming such as TCP and UDP socket servers, offering a powerful and flexible architecture for building scalable network applications.

Pros

  • High performance and scalability due to its non-blocking I/O model
  • Extensive protocol support, including HTTP, WebSocket, SSL/TLS, and custom protocols
  • Well-documented with a large and active community
  • Flexible and customizable with a rich set of built-in features

Cons

  • Steep learning curve for developers new to asynchronous programming
  • Can be overkill for simple network applications
  • Requires careful handling of concurrency and thread safety
  • Some users report occasional stability issues in certain edge cases

Code Examples

  1. Creating a simple HTTP server:
public class HttpServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new HttpServerCodec());
                     ch.pipeline().addLast(new HttpHelloWorldServerHandler());
                 }
             });

            Channel ch = b.bind(8080).sync().channel();
            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
  1. Implementing a simple echo client:
public class EchoClient {
    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new EchoClientHandler());
                 }
             });

            ChannelFuture f = b.connect("localhost", 8080).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
  1. Using WebSocket with Netty:
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast(new WebSocketServerProtocolHandler("/websocket"));
        pipeline.addLast(new WebSocketFrameHandler());
    }
}

Getting Started

To use Netty in your project, add the following dependency to your Maven pom.xml:

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.86.Final</version>
</dependency>

For Gradle, add this to your build.gradle:

implementation 'io.netty:netty-all:4.1.86.Final'

After adding the dependency, you can start using Netty by creating a Bootstrap or ServerBootstrap instance and configuring your channel handlers as shown in the code examples above.

Competitor Comparisons

TCP/HTTP/UDP/QUIC client/server with Reactor over Netty

Pros of Reactor Netty

  • Built on top of Netty, providing a higher-level reactive API
  • Seamless integration with Project Reactor for reactive programming
  • Simplified asynchronous programming model with Flux and Mono

Cons of Reactor Netty

  • Steeper learning curve for developers new to reactive programming
  • Smaller community and ecosystem compared to Netty
  • May introduce additional overhead due to the reactive layer

Code Comparison

Netty (traditional approach):

bootstrap.group(group)
    .channel(NioServerSocketChannel.class)
    .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new HttpServerCodec());
        }
    });

Reactor Netty (reactive approach):

HttpServer.create()
    .route(routes ->
        routes.get("/hello", (request, response) ->
            response.sendString(Mono.just("Hello, World!"))))
    .bindNow();

The Reactor Netty example demonstrates a more concise and declarative approach to setting up an HTTP server, leveraging the reactive programming model. The Netty example shows the traditional imperative style, offering more fine-grained control over the server configuration.

High performance non-blocking webserver

Pros of Undertow

  • Simpler API and easier to use for web applications
  • Built-in support for WebSockets and server-sent events
  • Lightweight and optimized for performance in web server scenarios

Cons of Undertow

  • Less flexible for non-HTTP protocols
  • Smaller community and ecosystem compared to Netty
  • Limited documentation and learning resources

Code Comparison

Undertow server setup:

Undertow server = Undertow.builder()
    .addHttpListener(8080, "localhost")
    .setHandler(new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getResponseSender().send("Hello World");
        }
    }).build();
server.start();

Netty server setup:

EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
     .channel(NioServerSocketChannel.class)
     .childHandler(new ChannelInitializer<SocketChannel>() {
         @Override
         public void initChannel(SocketChannel ch) throws Exception {
             ch.pipeline().addLast(new HttpServerCodec());
             ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpObject>() {
                 @Override
                 protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
                     // Handle request
                 }
             });
         }
     });
    ChannelFuture f = b.bind(8080).sync();
    f.channel().closeFuture().sync();
} finally {
    workerGroup.shutdownGracefully();
    bossGroup.shutdownGracefully();
}
14,281

Vert.x is a tool-kit for building reactive applications on the JVM

Pros of Vert.x

  • Higher-level abstraction, simplifying development of reactive applications
  • Built-in support for various protocols and services (HTTP, WebSockets, databases)
  • Polyglot nature, supporting multiple programming languages

Cons of Vert.x

  • Steeper learning curve for developers new to reactive programming
  • Less fine-grained control over low-level networking operations
  • Potentially higher memory footprint due to additional abstractions

Code Comparison

Netty (low-level networking):

bootstrap.group(group)
    .channel(NioServerSocketChannel.class)
    .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new EchoServerHandler());
        }
    });

Vert.x (high-level abstraction):

vertx.createHttpServer().requestHandler(req -> {
    req.response()
        .putHeader("content-type", "text/plain")
        .end("Hello from Vert.x!");
}).listen(8080);

The code comparison illustrates the difference in abstraction levels. Netty provides more granular control over the networking stack, while Vert.x offers a more concise and higher-level API for common tasks like creating an HTTP server.

Asynchronous Http and WebSocket Client library for Java

Pros of async-http-client

  • Higher-level abstraction for HTTP client operations
  • Simpler API for common HTTP tasks
  • Built-in support for various authentication methods

Cons of async-http-client

  • Less flexible for non-HTTP use cases
  • Smaller community and fewer contributors
  • More limited in terms of low-level network programming capabilities

Code Comparison

async-http-client:

AsyncHttpClient client = Dsl.asyncHttpClient();
Future<Response> f = client.prepareGet("http://www.example.com/").execute();
Response r = f.get();

Netty:

Bootstrap b = new Bootstrap();
b.group(group)
 .channel(NioSocketChannel.class)
 .handler(new HttpClientInitializer());
Channel ch = b.connect(HOST, PORT).sync().channel();

Key Differences

  • Netty is a general-purpose networking framework, while async-http-client is specifically designed for HTTP client operations
  • Netty provides more control over low-level networking details, whereas async-http-client offers a higher-level API for HTTP requests
  • async-http-client is built on top of Netty, leveraging its core functionality for network operations

Use Cases

  • Choose Netty for building custom network protocols or low-level networking applications
  • Opt for async-http-client when focusing on HTTP client operations and requiring a simpler API

Community and Ecosystem

  • Netty has a larger community, more contributors, and a wider range of third-party libraries
  • async-http-client has a smaller but dedicated community, focusing specifically on HTTP client use cases
11,358

The Java gRPC implementation. HTTP/2 based RPC

Pros of gRPC-Java

  • Higher-level abstraction for building RPC systems
  • Built-in support for protocol buffers and HTTP/2
  • Streamlined API for defining services and methods

Cons of gRPC-Java

  • Less flexible for non-RPC use cases
  • Steeper learning curve for developers new to gRPC concepts
  • More opinionated architecture, potentially limiting customization

Code Comparison

gRPC-Java service definition:

public class HelloWorldServer {
  @Override
  public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
  }
}

Netty server handler:

public class HelloWorldServerHandler extends ChannelInboundHandlerAdapter {
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf in = (ByteBuf) msg;
    System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));
    ctx.write(in);
  }
}

gRPC-Java is better suited for building RPC systems with a focus on service definitions and method calls, while Netty provides more low-level control over network communication and can be used for a wider range of protocols and use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build project

Netty Project

Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients.

Links

How to build

For the detailed information about building and developing Netty, please visit the developer guide. This page only gives very basic information.

You require the following to build Netty:

Note that this is build-time requirement. JDK 5 (for 3.x) or 6 (for 4.0+ / 4.1+) is enough to run your Netty-based application.

Branches to look

Development of all versions takes place in each branch whose name is identical to <majorVersion>.<minorVersion>. For example, the development of 3.9 and 4.1 resides in the branch '3.9' and the branch '4.1' respectively.

Usage with JDK 9+

Netty can be used in modular JDK9+ applications as a collection of automatic modules. The module names follow the reverse-DNS style, and are derived from subproject names rather than root packages due to historical reasons. They are listed below:

  • io.netty.all
  • io.netty.buffer
  • io.netty.codec
  • io.netty.codec.dns
  • io.netty.codec.haproxy
  • io.netty.codec.http
  • io.netty.codec.http2
  • io.netty.codec.memcache
  • io.netty.codec.mqtt
  • io.netty.codec.redis
  • io.netty.codec.smtp
  • io.netty.codec.socks
  • io.netty.codec.stomp
  • io.netty.codec.xml
  • io.netty.common
  • io.netty.handler
  • io.netty.handler.proxy
  • io.netty.resolver
  • io.netty.resolver.dns
  • io.netty.transport
  • io.netty.transport.epoll (native omitted - reserved keyword in Java)
  • io.netty.transport.kqueue (native omitted - reserved keyword in Java)
  • io.netty.transport.unix.common (native omitted - reserved keyword in Java)
  • io.netty.transport.rxtx
  • io.netty.transport.sctp
  • io.netty.transport.udt

Automatic modules do not provide any means to declare dependencies, so you need to list each used module separately in your module-info file.