FileTransfer/FileTransferService/src/main/java/com/xiaoliu/handler/FileReceiveServerHandler.java

63 lines
1.8 KiB
Java

package com.xiaoliu.handler;
import com.xiaoliu.codec.Codec;
import com.xiaoliu.protocol.attribute.Attributes;
import com.xiaoliu.protocol.request.LoginPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import java.io.FileOutputStream;
import java.io.IOException;
@Slf4j
public class FileReceiveServerHandler extends ChannelInboundHandlerAdapter {
static FileOutputStream outputStream;
static long fileLength;
private static long readLength;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
LoginPacket loginPacket = ctx.channel().attr(Attributes.userAttr).get();
ByteBuf byteBuf = (ByteBuf) msg;
int type = byteBuf.getInt(0);
if (type != Codec.TYPE) {
loginPacket.setReadLength(loginPacket.getReadLength()+byteBuf.readableBytes());
//readLength += byteBuf.readableBytes();
writeToFile(byteBuf, loginPacket.getFileOutputStream());
sendComplete(loginPacket);
} else {
super.channelRead(ctx, msg);
}
}
private void writeToFile(ByteBuf byteBuf, FileOutputStream outputStream) throws IOException {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
outputStream.write(bytes);
byteBuf.release();
}
private void sendComplete(long readLength) throws IOException {
if (readLength >= fileLength) {
log.info("文件接收完成.....");
outputStream.close();
}
}
private void sendComplete(LoginPacket loginPacket) throws IOException {
if (loginPacket.getReadLength() >= loginPacket.getFileLength()) {
log.info("文件接收完成...");
loginPacket.setExec(false);
loginPacket.setReadLength(0);
loginPacket.getFileOutputStream().close();
}
}
}