JavaSE-21.3.7【TCP通信程序练习6】
1 package day12.lesson3.p6; 2 3 import java.io.*; 4 import java.net.Socket; 5 6 /* 7 3.8 TCP通信程序练习6 8 9 案例需求 10 客户端:数据来自于文本文件,接收服务器反馈 11 服务器:接收到的数据写入文本文件,给出反馈,代码用线程进行封装,为每一个客户端开启一个线程 12 案例分析 13 创建客户端对象,创建输入流对象指向文件,每读入一行数据就给服务器输出一行数据,输出结束后使用shutdownOutput()方法告知服务端传输结束 14 创建多线程类,在run()方法中读取客户端发送的数据,为了防止文件重名,使用计数器给文件名编号,接受结束后使用输出流给客户端发送反馈信息。 15 创建服务端对象,每监听到一个客户端则开启一个新的线程接受数据。 16 客户端接受服务端的回馈信息 17 */ 18 public class ClientDemo { 19 public static void main(String[] args) throws IOException{ 20 Socket s = new Socket("MSI-YUBABY", 10000); 21 22 BufferedReader br = new BufferedReader(new FileReader("stage2\\src\\day12\\lesson3\\p6\\src.txt")); 23 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 24 25 String line; 26 while ((line=br.readLine()) != null){ 27 bw.write(line); 28 bw.newLine(); 29 bw.flush(); 30 } 31 32 s.shutdownOutput(); //表示输出结束 33 34 //接收反馈 35 BufferedReader brClient = new BufferedReader(new InputStreamReader(s.getInputStream())); 36 String data = brClient.readLine(); // 37 System.out.println("服务器的反馈:" + data); 38 39 br.close(); 40 s.close(); 41 } 42 }
1 package day12.lesson3.p6; 2 3 import java.io.*; 4 import java.net.ServerSocket; 5 import java.net.Socket; 6 7 public class ServerDemo { 8 public static void main(String[] args) throws IOException { 9 ServerSocket ss = new ServerSocket(10000); 10 11 while (true){ 12 Socket s = ss.accept(); 13 new Thread(new ServerThread(s)).start(); 14 } 15 16 // ss.close(); //实际上,一般来说服务器是不关闭了,所以此处先不close了 17 } 18 } 19 20 class ServerThread implements Runnable{ 21 private Socket s; 22 23 public ServerThread(Socket s) { 24 this.s = s; 25 } 26 27 @Override 28 public void run() { 29 try { 30 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); 31 // BufferedWriter bw = new BufferedWriter(new FileWriter("stage2\\src\\day12\\lesson3\\p6\\tar.txt")); 32 33 //解决名称冲突问题(场景:服务器打开一个不动,多个客户端上交同名文件) 34 int count = 0; 35 File file = new File("stage2\\src\\day12\\lesson3\\p6\\tar[" + count + "].txt"); 36 while (file.exists()){ 37 count++; 38 file = new File("stage2\\src\\day12\\lesson3\\p6\\tar[" + count + "].txt"); 39 } 40 BufferedWriter bw = new BufferedWriter(new FileWriter(file)); 41 42 String linel; 43 while ((linel=br.readLine()) != null){ 44 bw.write(linel); 45 bw.newLine(); 46 bw.flush(); 47 } 48 49 //给出反馈 50 BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 51 bwServer.write("文件上传成功"); 52 bwServer.newLine(); 53 bwServer.flush(); 54 55 s.close(); 56 }catch (IOException e){ 57 e.printStackTrace(); 58 } 59 } 60 }
src.txt
hello world java 886 do u love it? i love it very much
tar.txt tar[0].txt tar[1].txt tar[...].txt
hello world java 886 do u love it? i love it very much