package liu.net.udpupload; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class UploadClient { public static void main(String[] args) throws UnknownHostException, IOException { /* 上傳文本的客戶端。讀取本地文本數據,發送給服務端,服務端接收完畢後,回饋「上傳成功」 */ System.out.println("客戶端啓動。。。"); //客戶端 socket Socket s = new Socket("127.0.0.1",8890); //1.肯定數據源,本地文件 BufferedReader bufr = new BufferedReader(new FileReader("text.txt")); //2.肯定目的地 socket 輸出流 //BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); PrintWriter pw = new PrintWriter(s.getOutputStream(),true); String line = null; while((line=bufr.readLine())!=null){ pw.println(line); } //用socket的禁用流輸出方法,告訴服務端文件傳說完成,不然服務端不知道文件傳輸完成 s.shutdownOutput(); //3.經過 socket 讀取服務端返回的數據 BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); String lineIn = bufIn.readLine(); System.out.println(lineIn); //關閉 bufr.close(); s.close(); System.out.println("客戶端關閉成功"); } }
package liu.net.udpupload; import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class UploadServer { public static void main(String[] args) throws IOException { //上傳文本到服務端,服務端接收數據並存儲到文件中,服務端接收完畢後,服務端回饋「接收成功」 System.out.println("服務端啓動。。。"); //1.服務端對象 ServerSocket ss= new ServerSocket(8890); //2.獲取客戶端 Socket s = ss.accept(); //3.獲取讀取流 BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); //4.肯定目的文件 PrintWriter pw = new PrintWriter(new FileWriter("server.txt"),true); //5.頻繁讀寫 String line = null; while((line=bufIn.readLine())!=null){ pw.println(line); } //6.給客戶端返回信息 PrintWriter out = new PrintWriter(s.getOutputStream(),true); out.println("上傳成功"); //7.關閉資源 pw.close(); s.close(); ss.close(); System.out.println("服務端成功關閉"); } }