问题遇到的现象和发生背景
在进行文件传输时,断点跟进发现,客户端已经将文件,传输到服务端,对应的处理类却没有收到
问题相关代码,请勿粘贴截图
@Slf4j
@Component
public class NewByteServerHandler extends ChannelInboundHandlerAdapter {
private static NewByteServerHandler newByteServerHandler;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@PostConstruct
public void init() {
newByteServerHandler = this;
}
/**
* 保存客户端IP
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
byte[] head = {0x50, 0x52, 0x4f, 0x58, 0x59, 0x20, 0x54, 0x43, 0x50, 0x34, 0x20};
for (int i = 0; i < head.length; i++) {
if (in.getByte(i) != head[i]) {
//报文头不符合nginx的报文头格式
// log.info("不符合Nginx的报文头格式!");
// ctx.close();
ctx.fireChannelRead(msg);
return;
}
}
byte[] dataHead = new byte[head.length];
in.readBytes(dataHead);
List<String> addressInfoList = new ArrayList<>();
StringBuilder info = new StringBuilder();
byte lastB = 0;
byte b = in.readByte();
//找到以0d0a结尾
while (b != 0x0a || lastB != 0x0d) {
if (b == 0x20 || b == 0x0d) {
addressInfoList.add(info.toString());
info = new StringBuilder();
} else {
info.append((char) b);
}
lastB = b;
b = in.readByte();
}
}
}
protected void initChannel(SocketChannel channel) throws Exception {
EventExecutorGroup bus = new DefaultEventExecutorGroup(1);
ChannelPipeline p = channel.pipeline();
//tcp 解析nginx 真实IP
p.addLast(new NewByteServerHandler());
p.addLast(new ObjectEncoder());
p.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingConcurrentResolver(null)));
//用户在创建链接时进行通道信息的保存
p.addLast(new LoginRequestHandler());
//大文件传输处理器
p.addLast(new ChunkedWriteHandler());
//文件处理
p.addLast(bus,new FileUploadHandler());
//其他业务处理
p.addLast(new ServerHandler());
}
运行结果及报错内容
无报错
我的解答思路和尝试过的方法
尝试解决的方案就时在客户端发送文件前进行休眠一定的毫秒数,但也不能保证百分百成功
客户端文件发送代码
public void channelActive(ChannelHandlerContext ctx) throws InterruptedException {
/**
* 传小文件会出现服务端解析真实IP 后无发给下一个handler 传递的情况
* 因此在在加延时发送
*/
Thread.sleep(60);
if (fileUploadFile!= null){}
我想要达到的结果
每次文件发送都可以成功