공부방/Netty 서버

Netty 서버 시작하기(1) - Echo Server 만들기

한우는 맛있어 2023. 1. 31. 01:57

개인 프로젝트로 Netty 채팅 서버를 만들어 보는 것에 앞서서 Netty에 대해 간략하게 학습하고자합니다.


Netty 서버를 사용하는 이유?

고성능

  • Non-blocking Asynchronous 처리가 기본
  • 적은 스레드로 많은 요청을 처리
  • GC부하를 최소화하는 Zero-copy ByteBuffer 지원

쓰기 편한다.

  • 각종 네트워크 프로토콜 (코덱) 기본 지원
  • 필요한 부분을 쉽게 조립해 쓸 수 있는 구조
  • 잘 문서화된 Javadoc 
  • 종속성이 낮다 -> JDK 5(Netty 3.x) 또는 6(Netty 4.x)이면 충분

Netty에서 살펴봐야되는 핵심 요소(인터페이스)

 

Netty 구성 요소 간략 구성도

Netty 핵심 인터페이스 간략 구성도

 


Netty Echo 서버 만들기

디렉토리 구조

EchoServer.java

package nettystartup.h1.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

final class EchoServer {
    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 EchoServerHandler());

            ChannelFuture f = b.bind(8011).sync();
            System.err.println("Ready for 0.0.0.0:8011");
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

 

EchoServerHandler.java

// modified from io.netty.example.echo
package nettystartup.h1.echo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

@Sharable
class EchoServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ctx.writeAndFlush(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

 

결과

 

 

참고 사이트

https://netty.io/wiki/user-guide-for-4.x.html

 

Netty.docs: User guide for 4.x

Preface The Problem Nowadays we use general purpose applications or libraries to communicate with each other. For example, we often use an HTTP client library to retrieve information from a web server and to invoke a remote procedure call via web services.

netty.io

https://netty.io/

 

Netty: Home

Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. Netty is an NIO client server framework which enables quick and easy development of network applications

netty.io