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

49 lines
1.3 KiB
Java

package com.xiaoliu.handler;
import com.xiaoliu.codec.Codec;
import com.xiaoliu.protocol.FilePacket;
import com.xiaoliu.protocol.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
@Slf4j
public class MyServerHandler extends ChannelInboundHandlerAdapter {
public static File file;
public static FileOutputStream outputStream;
public MyServerHandler() throws FileNotFoundException {
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(msg);
ByteBuf byteBuf = (ByteBuf) msg;
int type = byteBuf.getInt(0);
if (type != Codec.TYPE) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
outputStream.write(bytes);
byteBuf.release();
} else {
Packet packet = Codec.INSTANCE.decode(byteBuf);
if (packet instanceof FilePacket) {
FilePacket filePacket = (FilePacket) packet;
outputStream = new FileOutputStream("./receive-" + filePacket.getFile().getName());
ByteBuf byteBuf1 = ctx.channel().alloc().ioBuffer();
Codec.INSTANCE.encode(byteBuf1, filePacket);
ctx.channel().writeAndFlush(byteBuf1);
}
}
}
}