JavaSE-21.3.4【TCP通信程序练习3】
1 package day12.lesson3.p3; 2 3 import java.io.*; 4 import java.net.Socket; 5 6 /* 7 3.5 TCP通信程序练习3 8 9 案例需求 10 客户端:数据来自于键盘录入,直到输入的数据是886,发送数据结束 11 服务端:接受到的数据写入文本文件中 12 案例分析 13 客户端创建对象,使用键盘录入循环接受数据,接受一行发送一行,直到键盘录入886为止 14 服务端创建对象,创建输出流对象指向文件,每接受一行数据后使用输出流输出到文件中,直到接受到null为止 15 */ 16 public class ClientDemo { 17 public static void main(String[] args) throws IOException { 18 Socket socket = new Socket("MSI-YUBABY", 10000); 19 20 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 21 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 22 23 String line; 24 while ((line=br.readLine()) != null){ 25 if("886".equals(line)){ 26 break; 27 } 28 29 bw.write(line); 30 bw.newLine(); 31 bw.flush(); 32 } 33 34 socket.close(); 35 } 36 }
1 package day12.lesson3.p3; 2 3 import javax.net.ssl.SSLServerSocket; 4 import java.io.*; 5 import java.net.ServerSocket; 6 import java.net.Socket; 7 8 public class ServerDemo { 9 public static void main(String[] args) throws IOException { 10 ServerSocket ss = new ServerSocket(10000); //创建服务器Socket对象 11 12 Socket s = ss.accept(); //监听客户端连接,返回一个对应的Socket对象 13 14 //接收数据 15 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); 16 BufferedWriter bw = new BufferedWriter(new FileWriter("stage2\\src\\day12\\lesson3\\p3\\s.txt")); 17 18 String line; 19 while ((line=br.readLine()) != null){ 20 bw.write(line); 21 bw.newLine(); 22 bw.flush(); 23 } 24 25 bw.close(); 26 ss.close(); 27 } 28 }
s.txt
hello world java do u love it?