package com.ard.utils.tcp;
|
|
import io.netty.buffer.ByteBuf;
|
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.SimpleChannelInboundHandler;
|
import lombok.extern.slf4j.Slf4j;
|
|
import javax.xml.bind.DatatypeConverter;
|
|
/**
|
* @Description: tcp客户端处理
|
* @ClassName: NettyTcpClientHandler
|
* @Author: 刘苏义
|
* @Date: 2023年06月25日17:02
|
* @Version: 1.0
|
**/
|
@Slf4j
|
public class NettyTcpClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
|
@Override
|
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg){
|
// 处理接收到的消息
|
byte[] byteArray = new byte[msg.readableBytes()];
|
msg.getBytes(msg.readerIndex(), byteArray);
|
String hexString = DatatypeConverter.printHexBinary(byteArray);
|
|
log.info("Received: " + hexString);
|
}
|
|
@Override
|
public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
// 当客户端连接成功后,发送消息给服务器
|
ByteBuf message = ctx.alloc().buffer();
|
message.writeBytes("Hello, Server!".getBytes());
|
ctx.writeAndFlush(message);
|
}
|
|
@Override
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
|
// 发生异常时的处理
|
cause.printStackTrace();
|
ctx.close();
|
}
|
}
|