一 点睛
Netty 作为 NIO 框架,自然支持文件传输功能。本篇演示如何使用 Netty 进行远程发送文件。
二 待发送的文件
package netty.file;
import java.io.File;
import java.io.Serializable;
/**
* @className: MySendFile
* @description: 待发送的文件
* @date: 2022/5/28
* @author: cakin
*/
public class MySendFile implements Serializable {
private static final long serialVersionUID = 1L;
// 文件
private File file;
// 文件名
private String fileName;
// 开始位置
private int start;
// 结束位置
private int end;
// 数据
private byte[] bytes;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
三 服务端
1 主程序类
package netty.file;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class MyNettyServerTest {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
ChannelFuture channelFuture = serverBootstrap
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)