package cn.upload;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class UploadServer {
public static void main(String[] args) throws Exception {
System.out.println("服务器已启动, 绑定12345端口.");
ServerSocket serverSocket = new ServerSocket(12345);
while(true){
final Socket socket=serverSocket.accept();
new Thread(){
public void run() {
try {
// 3.读取文件名
// 字节流可以读写各种类型的数据
InputStream is = socket.getInputStream();
// 字符流只能读字符
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(socket.getOutputStream());
String filename = br.readLine();
// 3.1.读取文件大小
long length = Long.parseLong(br.readLine());
// 4.判断文件是否存在, 将结果发回客户端
File dir = new File("upload");
dir.mkdir();
File file = new File(dir, filename);
// 文件存在, 大小一致代表已上传过了
if (file.exists() && file.length() == length) {
ps.println("存在");
socket.close();
return;
} else {
// 不存在是0, 存在则是传了一半的大小
ps.println(file.length());
}
String ip = socket.getInetAddress().getHostAddress();
System.out.println(ip + (file.exists() ? "断点续传:" : "开始上传: ") + file.getName());
long start = System.currentTimeMillis();
// 7.定义FileOutputStream, 从网络读取数据, 存储到本地
FileOutputStream fos = new FileOutputStream(file, true);
byte[] buffer = new byte[1024];
int len;
// 文件可能是任意类型, 所以使用字节流读取
while ((len = is.read(buffer)) != -1)
fos.write(buffer, 0, len);
fos.close();
socket.close();
long end = System.currentTimeMillis();
System.out.println(ip + "上传完毕: " + file.getName() + ", 耗时: " + (end - start) + "毫秒.");
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
最近下载更多
2673747024 LV7
2021年1月9日
1106547553 LV10
2020年6月25日
可可_西里 LV11
2020年1月2日
litaosb LV5
2019年12月11日
1126055836 LV15
2019年6月17日
18832034896 LV2
2019年5月31日
灵依ziNing LV7
2019年5月10日
abcd22311 LV1
2019年1月3日
841713241 LV2
2018年12月29日
kenpfang LV18
2018年6月14日

最近浏览