Notice
Recent Posts
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- recoil
- 자바
- netty
- 백엔드 설정
- service
- Kotlin
- 네티 클라이언트
- 네티 서버
- JWT
- 배열
- 스프링부트
- toyproject
- 기초설정
- springboot
- Spring
- 팀프로젝트
- react
- axios
- Spring Boot
- controller
- Java
- 프로젝트
- 코틀린
- 클래스
- Repository
- 자료형
- 도커
- Security
- MySQL
- 채팅
Archives
- Today
- Total
hyuko
Netty Client 본문
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 |