59 lines
1.6 KiB
Java
59 lines
1.6 KiB
Java
package net.zb.examination.ftp.command;
|
|
|
|
import cn.hutool.core.util.StrUtil;
|
|
import io.netty.channel.ChannelHandlerContext;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import net.zb.examination.ftp.AbstractCommand;
|
|
import net.zb.examination.ftp.UserContainer;
|
|
import net.zb.examination.ftp.constant.CommandEnum;
|
|
import net.zb.examination.ftp.constant.FtpCommand;
|
|
import net.zb.examination.ftp.constant.UserInfo;
|
|
|
|
import java.io.File;
|
|
import java.io.FileInputStream;
|
|
import java.io.OutputStream;
|
|
import java.net.Socket;
|
|
|
|
/**
|
|
* <p></p>
|
|
*
|
|
* @author bin.zhang
|
|
* <p/>
|
|
* Revision History:
|
|
* 2020/04/18, 初始化版本
|
|
* @version 1.0
|
|
**/
|
|
@Slf4j
|
|
@FtpCommand(value = CommandEnum.GET)
|
|
public class GetCommand extends AbstractCommand {
|
|
|
|
|
|
@Override
|
|
public String process(ChannelHandlerContext ctx, String[] msg) {
|
|
UserInfo userInfo = UserContainer.getUserInfo(ctx.channel().id());
|
|
if (userInfo == null) {
|
|
ctx.close();
|
|
return null;
|
|
}
|
|
String path = StrUtil.addSuffixIfNot(userInfo.getDir(), File.separator) + msg[1];
|
|
File file = new File(path);
|
|
if (!file.isFile()) {
|
|
return "文件不存在";
|
|
}
|
|
try (FileInputStream in = new FileInputStream(file); Socket dataSocket = new Socket(userInfo.getAddress(), userInfo.getPort()); OutputStream out = dataSocket.getOutputStream()) {
|
|
ctx.writeAndFlush("150 Opening data connection.\r\n");
|
|
int bufSize = 1024 * 64;
|
|
byte buf[] = new byte[bufSize];
|
|
int nread;
|
|
while ((nread = in.read(buf)) > 0) {
|
|
out.write(buf, 0, nread);
|
|
}
|
|
ctx.writeAndFlush("226 transfer complete\r\n");
|
|
} catch (Exception e) {
|
|
log.error("传输文件失败", e);
|
|
return "未知异常";
|
|
}
|
|
return null;
|
|
}
|
|
}
|