한우는 맛있어
소문난 한우 맛집
한우는 맛있어
전체 방문자
오늘
어제
  • 분류 전체보기 (6)
    • 개인 프로젝트 (0)
    • 공부방 (6)
      • Java (2)
      • Web (1)
      • Netty 서버 (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 예외
  • Synchronos
  • 예외 처리
  • 동기
  • Netty 기초
  • Non - Blocking
  • 에러
  • 논 블로킹
  • Java
  • 비동기
  • Asychronos
  • 블로킹
  • error
  • try-with-resource
  • blocking
  • Exception

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
한우는 맛있어

소문난 한우 맛집

Netty  서버 시작하기(1) -  Echo Server 만들기
공부방/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)이면 충분
    •  요구 명세서 링크 :   https://netty.io/wiki/requirements-for-4.x.html 

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

  • Channel
    • 읽기, 쓰기, 연결(connect), 바인드(bind)등의 I/O 작업을 할 수 있는 요소 또는 네트워크 연결
    • 모든 I/O 작업은 비동기 -> ChannelFuture
    • https://netty.io/4.1/api/io/netty/channel/Channel.html
  • ChannelFuture
    • Channel의 I/O 작업의 결과
    • ChannelFutureListener를 등록 결과에 따른 작업
    • https://netty.io/4.1/api/io/netty/channel/ChannelFuture.html
  • ChannelHandler
    • Netty의 핵심 요소!
    • Netty의 I/O 이벤트를 처리하는 인터페이스
    • ChannelInboundHandlerAdapter
    • ChannelOutboundHandlerAdapter
    • https://netty.io/4.1/api/io/netty/channel/ChannelHandler.html
  • ChannelHandlerContext
    • ChannelHandler는 ChannelHandlerContext를 통해
    • 다음 ChannelHandler에게 이벤트를 넘기거나,
    • 동적으로 ChannelPipeline을 변경할 수 있음
    • https://netty.io/4.1/api/io/netty/channel/ChannelHandlerContext.html
  • ChannelPipeline
    • Channel에 드나드는 inbound / outbound 이벤트를 처리
    • Intercepting Filter 패턴 처리, ChannelHandler 리스트
    • https://netty.io/4.1/api/io/netty/channel/ChannelPipeline.html
  • EventLoop
    • 등록된 Channel들의 모든 I/O 작업을 처리
    • 구현체 NioEventLoopGroup를 주로 사용
    • https://netty.io/4.1/api/io/netty/channel/EventLoop.html

 

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

 

'공부방 > Netty 서버' 카테고리의 다른 글

Netty 서버 시작하기 (2) - 시간 서버 만들기  (0) 2023.02.06
    '공부방/Netty 서버' 카테고리의 다른 글
    • Netty 서버 시작하기 (2) - 시간 서버 만들기
    한우는 맛있어
    한우는 맛있어
    한우를 좋아하는 개린이(개발 어린이) 블로그입니다.

    티스토리툴바