티스토리 뷰

JAVA/Netty

Netty 간단한 Client 코드 작성

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

1. Client 용 ChannelHandler 작성

public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(Unpooled.copiedBuffer("Woongs netty client!", CharsetUtil.UTF_8));
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		System.out.println("Client received: " + msg.toString(CharsetUtil.UTF_8));
	}
}
  • channelActive() 를 재정의하여 channel 이 생성되면 특정 문구를 write
  • channelRead() 를 재정의하여 서버로부터 메시지 수신

2. Client Bootstrap 작성

public class NettyClientMain {
	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
				.channel(NioSocketChannel.class)
				.remoteAddress(new InetSocketAddress("localhost", 8080))
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new NettyClientHandler());
					}
				});
			ChannelFuture f = b.connect().sync();
			f.channel().closeFuture().sync();
		} catch (Exception e) {

		}
	}
}
  • 클라이언트를 초기화 하기 위한 Bootstrap 객체 생성
  • 새로운 연결을 생성하고 인바운드 아웃바운드 데이터 처리 이벤트를 처리하기 위한 nioEventLoopGroup 객체 생성 및 할당
  • 서버로 연결하기 위한 InetSocketAddress 생성
  • 연결이 만들어지면 파이프라인에 NettyClientServer 추가
  • 모든 준비가 완료되면 Bootstrap.connect() 호출해서 연결.

3. 결과

Server received : Woongs netty client!

 

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

Netty NioEventLoop 코드 레벨 분석  (0) 2021.07.12
Netty 간단한 서버 구축  (0) 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
글 보관함