1. 多个客户端上传到一个服务器的思考
通过while循环可以改进一个服务器接收多个客户端。
但是这个是有问题的。
如果是这种情况,假设我还有张三,李四,王五这三个人分别执行客户端
张三:好好学习.avi(100M) 256k
李四:天天向上.mp3(3M) 1M
王五:ILoveJava.txt(1k) 100M
这要等张三传完了,再去传李四……
2. 使用多线程改进:
(1)线程类UserThread:
1 package cn.itcast_15; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.io.OutputStreamWriter; 9 import java.net.Socket; 10 11 public class UserThread implements Runnable { 12 private Socket s; 13 14 public UserThread(Socket s) { 15 this.s = s; 16 } 17 18 @Override 19 public void run() { 20 try { 21 // 封装通道内的流 22 BufferedReader br = new BufferedReader(new InputStreamReader( 23 s.getInputStream())); 24 // 封装文本文件 25 // BufferedWriter bw = new BufferedWriter(new 26 // FileWriter("Copy.java")); 27 28 // 为了防止名称冲突 29 String newName = System.currentTimeMillis() + ".java"; 30 BufferedWriter bw = new BufferedWriter(new FileWriter(newName)); 31 32 String line = null; 33 while ((line = br.readLine()) != null) { // 阻塞 34 bw.write(line); 35 bw.newLine(); 36 bw.flush(); 37 } 38 39 // 给出反馈 40 BufferedWriter bwServer = new BufferedWriter( 41 new OutputStreamWriter(s.getOutputStream())); 42 bwServer.write("文件上传成功"); 43 bwServer.newLine(); 44 bwServer.flush(); 45 46 // 释放资源 47 bw.close(); 48 s.close(); 49 } catch (IOException e) { 50 e.printStackTrace(); 51 } 52 } 53 54 }
(2)客户端:
1 package cn.itcast_15; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileReader; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.io.OutputStreamWriter; 9 import java.net.Socket; 10 11 public class UploadClient { 12 public static void main(String[] args) throws IOException { 13 // 创建客户端Socket对象 14 Socket s = new Socket("192.168.12.92", 11111); 15 16 // 封装文本文件 17 // BufferedReader br = new BufferedReader(new FileReader( 18 // "InetAddressDemo.java")); 19 BufferedReader br = new BufferedReader(new FileReader( 20 "ReceiveDemo.java")); 21 // 封装通道内流 22 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( 23 s.getOutputStream())); 24 25 String line = null; 26 while ((line = br.readLine()) != null) { // 阻塞 27 bw.write(line); 28 bw.newLine(); 29 bw.flush(); 30 } 31 32 // Socket提供了一个终止,它会通知服务器你别等了,我没有数据过来了 33 s.shutdownOutput(); 34 35 // 接收反馈 36 BufferedReader brClient = new BufferedReader(new InputStreamReader( 37 s.getInputStream())); 38 String client = brClient.readLine(); // 阻塞 39 System.out.println(client); 40 41 // 释放资源 42 br.close(); 43 s.close(); 44 } 45 }
(3)服务器端:
1 package cn.itcast_15; 2 3 import java.io.IOException; 4 import java.net.ServerSocket; 5 import java.net.Socket; 6 7 public class UploadServer { 8 public static void main(String[] args) throws IOException { 9 // 创建服务器Socket对象 10 ServerSocket ss = new ServerSocket(11111); 11 12 while (true) { 13 Socket s = ss.accept(); 14 new Thread(new UserThread(s)).start(); 15 } 16 } 17 }
时间: 2024-10-20 12:41:11