Java----TCP上传文件(线程池优化版)
作者:
Agoni7z
,
2024-05-08 11:13:37
,
所有人可见
,
阅读 14
Client
package com.text.A07text.text2;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 10000);
// 2.读取本地文件并写入服务器中
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("untitled\\src\\com\\text\\A07text\\text2"));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
// 往服务器写出结束标记
socket.shutdownOutput();
// 接收服务器的回写数据
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = br.readLine();
System.out.println(line);
socket.close();
}
}
Server
package com.text.A07text.text2;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;
public class Server {
public static void main(String[] args) throws IOException {
// 创建线程池对象
ThreadPoolExecutor pool = new ThreadPoolExecutor(
3, // 核心线程数量
16, // 线程池总大小
60, TimeUnit.SECONDS, // 空闲时间和单位
new ArrayBlockingQueue<>(2),//队列
Executors.defaultThreadFactory(),//线程工厂,让线程池如何创建线程对象
new ThreadPoolExecutor.AbortPolicy()// 阻塞队列
);
ServerSocket ss = new ServerSocket(10000);
while (true) {
Socket socket = ss.accept();
// 开启一条线程
// 一个用户对应服务端的一条线程
// new Thread(new MyRunnable(socket)).start();
pool.submit(new MyRunnable(socket));
}
}
}
Myrunnanble
package com.text.A07text.text2;
import java.io.*;
import java.net.Socket;
public class MyRunnable implements Runnable {
Socket socket;
public MyRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("untitled\\src\\com\\text\\A07text\\text2\\微信图片_20240310191552.jpg"));
int len;
byte[] bytes = new byte[1024];
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
//回写数据
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("上传成功");
bw.newLine();
bw.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//5. 释放资源
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}