TCP模拟实现文本文件上传Java代码
多线程Main代码:
new Thread(new TextUploadServer()).start(); new Thread(new TextUploadClient()).start();
客户端代码:
1 public class TextUploadClient implements Runnable { 2 @Override 3 public void run() { 4 try { 5 Socket socket = new Socket(InetAddress.getLocalHost(), 50001); 6 String path = "D:\\src.txt"; 7 BufferedReader bufferedReader = new BufferedReader(new FileReader(path)); 8 //可用PrintWriter代替,更简单 9 BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 10 11 String line = null; 12 while((line = bufferedReader.readLine()) != null){ 13 bufferedWriter.write(line);//只需改为printWriter.println(line); 14 bufferedWriter.newLine(); 15 bufferedWriter.flush(); 16 } 17 socket.shutdownOutput(); 18 19 BufferedReader backReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 20 String res = backReader.readLine(); 21 22 System.out.println(res); 23 24 bufferedReader.close(); 25 socket.close(); 26 } 27 catch (Exception e) { 28 e.printStackTrace(); 29 } 30 } 31 32 }
服务端代码实现:
1 public class TextUploadServer implements Runnable { 2 3 @Override 4 public void run() { 5 6 try { 7 ServerSocket ss = new ServerSocket(50001); 8 Socket socket = ss.accept(); 9 10 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 11 BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:\\tar.txt")); 12 13 String line = null; 14 while((line = bufferedReader.readLine()) != null){ 15 bufferedWriter.write(line); 16 bufferedWriter.newLine(); 17 //bufferedWriter.flush(); 18 } 19 20 BufferedWriter returnWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 21 returnWriter.write("Txt文本上传成功!!"); 22 returnWriter.newLine(); 23 returnWriter.flush(); 24 25 bufferedWriter.close(); 26 socket.close(); 27 ss.close(); 28 29 } 30 catch (Exception e) { 31 // TODO Auto-generated catch block 32 e.printStackTrace(); 33 } 34 35 36 } 37 }