티스토리 뷰

JAVA/Netty

Netty 간단한 서버 구축

소농배 2021. 7. 11. 13:40

Sample Netty Server

1. ChannelHanlder 작성

  • ChannelHandler 는 이벤트를 수신하고 이벤트에 해당하는 비지니스 로직을 구현할 수 있는 컴포넌트
  • Netty Server 는 Inbound 이벤트에 반응해야 하므로 ChannelInboundHandler 인터페이스를 구현
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// msg 가 들어올때마다 호출
		ByteBuf in = (ByteBuf) msg;
		System.out.println("Server received : " + in.toString(CharsetUtil.UTF_8));
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// 마지막 메시지가 처리되었음을 핸들러에게 알림
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// 예외가 발생한 경우 호출
		cause.printStackTrace();
		ctx.close();
	}
}

2. SeverBootStrap 생성 및 ChannelHandler 등록

  • 서버를 실행하고 바인딩하는데 이용할 ServerBootStrap 객체를 생성
  • 새로운 연결 수락 및 데이터 읽기/쓰기와 강튼 이벤트 처리를 수행할 NioEventLoopGroup 인스턴스를 생성하고 할당
  • 서버가 바인딩하는 로컬 InetSocketAddress 지정
  • NettyServerHandler 인스턴스를 이용해 새로운 각 Channel 을 초기화
  • ServerBootstrap.bind() 를 호출해 서버를 바인딩
public class NettyMain {

	public static void main(String[] args) {

		NettyServerHandler nettyServerHandler = new NettyServerHandler();
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(group)
					 .channel(NioServerSocketChannel.class)
					 .localAddress(new InetSocketAddress(8080))
					 // 새로운 연결 수락 후 새로운 자식 Channel 생성한 후 NettyServerHanlder 를 파이프라인에 추가
					 .childHandler(new ChannelInitializer<SocketChannel>() {
					 	@Override
						 public void initChannel(SocketChannel channel) {
					 		channel.pipeline().addLast(nettyServerHandler);
						 }
					 });
			// 서버 바인딩 후 완료되기까지 대기
			ChannelFuture channelFuture = bootstrap.bind().sync();
			// 서버의 Channel 이 닫힐때까지 대기
			channelFuture.channel().closeFuture().sync();
		} catch (Exception e) {

		}
	}
}

3. 결과

curl -v http://localhost:8080 -d "Woongs"

 

Server received : POST / HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.54.0
Accept: */*
Content-Length: 6
Content-Type: application/x-www-form-urlencoded

Woongs

'JAVA > Netty' 카테고리의 다른 글

Netty NioEventLoop 코드 레벨 분석  (0) 2021.07.12
Netty 간단한 Client 코드 작성  (1) 2021.07.11
Netty 개념과 아키텍쳐  (0) 2021.07.11
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함