Java基础知识强化之网络编程笔记14:TCP之多个客户端上传到一个服务器的思考(多线程改进)

时间:2024-04-18 09:07:43

1. 多个客户端上传到一个服务器的思考

通过while循环可以改进一个服务器接收多个客户端。

但是这个是有问题的。
如果是这种情况,假设我还有张三,李四,王五这三个人分别执行客户端
   张三:好好学习.avi(100M)    256k
   李四:天天向上.mp3(3M)     1M
   王五:ILoveJava.txt(1k)    100M

这要等张三传完了,再去传李四……

2. 使用多线程改进:

(1)线程类UserThread:

 package cn.itcast_15;

 import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket; public class UserThread implements Runnable {
private Socket s; public UserThread(Socket s) {
this.s = s;
} @Override
public void run() {
try {
// 封装通道内的流
BufferedReader br = new BufferedReader(new InputStreamReader(
s.getInputStream()));
// 封装文本文件
// BufferedWriter bw = new BufferedWriter(new
// FileWriter("Copy.java")); // 为了防止名称冲突
String newName = System.currentTimeMillis() + ".java";
BufferedWriter bw = new BufferedWriter(new FileWriter(newName)); String line = null;
while ((line = br.readLine()) != null) { // 阻塞
bw.write(line);
bw.newLine();
bw.flush();
} // 给出反馈
BufferedWriter bwServer = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
bwServer.write("文件上传成功");
bwServer.newLine();
bwServer.flush(); // 释放资源
bw.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
} }

(2)客户端:

 package cn.itcast_15;

 import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket; public class UploadClient {
public static void main(String[] args) throws IOException {
// 创建客户端Socket对象
Socket s = new Socket("192.168.12.92", 11111); // 封装文本文件
// BufferedReader br = new BufferedReader(new FileReader(
// "InetAddressDemo.java"));
BufferedReader br = new BufferedReader(new FileReader(
"ReceiveDemo.java"));
// 封装通道内流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream())); String line = null;
while ((line = br.readLine()) != null) { // 阻塞
bw.write(line);
bw.newLine();
bw.flush();
} // Socket提供了一个终止,它会通知服务器你别等了,我没有数据过来了
s.shutdownOutput(); // 接收反馈
BufferedReader brClient = new BufferedReader(new InputStreamReader(
s.getInputStream()));
String client = brClient.readLine(); // 阻塞
System.out.println(client); // 释放资源
br.close();
s.close();
}
}

(3)服务器端:

 package cn.itcast_15;

 import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; public class UploadServer {
public static void main(String[] args) throws IOException {
// 创建服务器Socket对象
ServerSocket ss = new ServerSocket(11111); while (true) {
Socket s = ss.accept();
new Thread(new UserThread(s)).start();
}
}
}