JavaSE-21.3.5【TCP通信程序练习4】

 1 package day12.lesson3.p4;
 2 
 3 import java.io.*;
 4 import java.net.Socket;
 5 
 6 /*
 7 3.6 TCP通信程序练习4
 8 
 9     案例需求
10         客户端:数据来自于文本文件
11         服务器:接收到的数据写入文本文件
12         本例相等于实现一个文件上传下载功能
13     案例分析
14         创建客户端,创建输入流对象指向文件,从文件循环读取数据,每读取一行就使用输出流给服务器输出一行
15         创建服务端,创建输出流对象指向文件,从客户端接受数据,每接受一行就给文件中输出一行
16  */
17 public class ClientDemo {
18     public static void main(String[] args) throws IOException {
19         Socket s = new Socket("MSI-YUBABY", 10000);
20 
21         BufferedReader br = new BufferedReader(new FileReader("stage2\\src\\day12\\lesson3\\p4\\src.txt"));
22         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
23 
24         String line;
25         while ((line=br.readLine()) != null){
26             bw.write(line);
27             bw.newLine();
28             bw.flush();
29         }
30 
31         br.close();
32         s.close();
33     }
34 }
 1 package day12.lesson3.p4;
 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); //创建服务器Socket对象
10 
11         Socket s = ss.accept(); //监听客户端连接,返回一个对应的Socket对象
12 
13         //接收数据
14         BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
15         BufferedWriter bw = new BufferedWriter(new FileWriter("stage2\\src\\day12\\lesson3\\p4\\tar.txt"));
16 
17         String line;
18         while ((line=br.readLine()) != null){
19             bw.write(line);
20             bw.newLine();
21             bw.flush();
22         }
23 
24         bw.close();
25         ss.close();
26     }
27 }

src.txt

hello
world
java
do u love it?
i love it very much

tar.txt

hello
world
java
do u love it?
i love it very much

  

posted @ 2021-06-11 10:01  yub4by  阅读(41)  评论(0编辑  收藏  举报