不说啥了,直接上代码。。。。
package com.deos.service.uploadAnddownload;
import java.io.File;
import com.deos.service.DaoService;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetSocket;
public class DownloadService {
private Vertx vertx;
private DaoService daoServer;
private JsonObject config;
private NetServer server;
public DownloadService(Vertx vertx, DaoService daoServer,JsonObject config){
this.vertx = vertx;
this.daoServer = daoServer;
this.config=config;
server = vertx.createNetServer();
}
public void login(){
server.connectHandler(new Handler<NetSocket>() {
@Override
public void handle(NetSocket socket) {
System.out.println("传入的连接---!");
socket.handler(buffe1->{
String lia1 = new String( buffe1.getBytes());
System.out.println("开始读取客户端数据。。。。。。。"+lia1);
socket.write("1");//写个标记到前端
vertx.executeBlocking(future -> {
//文件下载
System.out.println("【文件下载】服务器:" + socket.remoteAddress() + " 正在运行中...");
socket.handler(buffer->{//第一个socket.handler
String path = new String(buffer.getBytes());
System.out.println("开始读取。。。。。。。"+path);
File file = new File(path); //客户端传来文件路径
System.out.println("文件长度=="+file.length()+"文件名=="+file.getName()+"文件绝对路径=="+file.getAbsolutePath());
if(file.exists()){
socket.write(String.valueOf(file.length()),"UTF-8");//传回客户端后台文件长度
socket.handler(buff->{//第二个socket.handler
String localFileSize = new String(buff.getBytes());//客户端文件的大小
System.out.println("localFileSize="+localFileSize);
// 定位文件指针到nPos位置
long offset=Long.parseLong(localFileSize);//指针位置,前端传过来的
System.out.println("---offset-----------"+offset);
vertx.fileSystem().open(path, new OpenOptions().setWrite(false).setCreate(false), result1 -> {
if (result1.succeeded()) {
result1.result().setReadBufferSize(8000).setReadPos(offset).handler(data -> {
socket.write(data);
if(socket.writeQueueFull()){
socket.pause();
socket.drainHandler(done -> {
socket.resume();
});
}
});
} else {
System.err.println("Oh oh ..." + result1.cause());
}
});
}).endHandler(v -> System.out.println());
}else{
System.err.println("后台文件不存在");
}
}).endHandler(v -> System.out.println());
socket.closeHandler(handler->{
System.out.println("socket下载关闭");
});
}, r -> {});
});
}});
}
public void initNetServer(){
login();
server.listen(8085, "192.168.0.10", result -> {
if (result.succeeded()) {
System.out.println("Server is now listening.......下载.............");
} else {
System.out.println("Failed to bind--------------");
}
});
}
}