hyuko

Netty Client 본문

Springboot

Netty Client

hyuko12 2024. 7. 19. 09:52
728x90
반응형

Netty config 설정

@Slf4j
@Configuration
@RequiredArgsConstructor
public class NettyClientConfig {

    @Bean
    public Bootstrap readBootstrap(ClientChannelInitializer nettyChannelInitializer) {
        log.info("bootstrap create for client");
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group()).channel(NioSocketChannel.class).handler(nettyChannelInitializer);

        return bootstrap;
    }


    @Bean(destroyMethod = "shutdownGracefully")
    public NioEventLoopGroup group() {
        return new NioEventLoopGroup();
    }


}

 

Encoder

public class ClientEncoder extends MessageToByteEncoder<byte[]> {

    @Override
    protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception {
        out.writeBytes(msg);
    }
}

 

Decoder

@Slf4j
public class ClientDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int funcCode = in.getByte(1) & 0xFF;
        int byteCount = in.getByte(2) & 0xFF;
        try {
            if (in.readableBytes() >= 5 + byteCount) {
                log.info("byteCount: {}", byteCount);
                ByteBuf response = in.readBytes(5 + byteCount);
                byte[] responseData = new byte[response.readableBytes()];
                response.readBytes(responseData);

                if (funcCode != 3) {
                    log.info("responseData: {}", Arrays.toString(responseData));
                }
                out.add(responseData);
                response.release();
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new IllegalArgumentException(e.getMessage());
        }

    }
}

 

ChannelInitializer

@Component
@RequiredArgsConstructor
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final ClientHandler clientHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        ClientDecoder decoder = new ClientDecoder();
        ClientEncoder encoder = new ClientEncoder();

        pipeline.addLast(decoder, encoder, clientHandler);
    }
}

 

Handler

@Slf4j
@RequiredArgsConstructor
@Component
@ChannelHandler.Sharable
public class ClientHandler extends SimpleChannelInboundHandler<byte[]> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
       

    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
      
    }

   
}
728x90
반응형

'Springboot' 카테고리의 다른 글

Spring Cloud Stream  (0) 2024.07.19
Netty 클라이언트와 서버의 차이점  (0) 2024.07.19
네티 서버 구현  (0) 2024.07.19
Netty  (0) 2024.07.19
spring security / 전체적인 흐름  (0) 2023.04.29