Java--优化利用TCP实现文件上传(多线程)
博客说明
文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!
图解
步骤
- 【客户端】输入流,从硬盘读取文件数据到程序中。
- 【客户端】输出流,写出文件数据到服务端。
- 【服务端】输入流,读取文件数据到服务端程序。
- 【服务端】输出流,写出文件数据到服务器硬盘中
优化
-
文件名称写死的问题
服务端,保存文件的名称如果写死,那么最终导致服务器硬盘,只会保留一个文件,建议使用系统时间优化,保证文件名称唯一
-
循环接收的问题
服务端使用循环改进,可以不断的接收不同用户的文件
-
效率问题
服务端,在接收大文件时,可能耗费几秒钟的时间,此时不能接收其他用户上传,所以,使用多线程技术优化
代码实现
服务器
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author ServerTCP
* @date 2020/4/25 10:51 上午
*/
public class ServerTCP {
public static void main(String[] args) throws IOException {
System.out.println("服务启动,等待连接中");
//创建ServerSocket对象,绑定端口,开始等待连接
ServerSocket ss = new ServerSocket(8888);
//循环接收
while (true) {
//接受accept方法,返回socket对象
Socket server = ss.accept();
//开启多线程
new Thread(() -> {
try (
//获取输入流对象
BufferedInputStream bis = new BufferedInputStream(server.getInputStream());
//创建输出流对象, 保存到本地 .
FileOutputStream fis = new FileOutputStream(System.currentTimeMillis() + ".jpg");
BufferedOutputStream bos = new BufferedOutputStream(fis);
) {
//读写数据
byte[] b = new byte[1024 * 8];
int len;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
//关闭 资源
bos.close();
bis.close();
server.close();
System.out.println("文件上传已保存");
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
}
客户端
import java.io.*;
import java.net.Socket;
/**
* @author ClientTCP
* @date 2020/4/25 10:58 上午
*/
public class ClientTCP {
public static void main(String[] args) throws IOException {
//创建输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("in.txt"));
//创建Socket
Socket client = new Socket("127.0.0.1", 8888);
//输出流
BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
//写出数据
byte[] b = new byte[1024 * 8];
int len;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();
}
System.out.println("文件已上传");
//关闭资源
bos.close();
client.close();
bis.close();
System.out.println("文件上传完成");
}
}
感谢
黑马程序员以及勤劳的自己
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。