客户端:
1 package WebProgramingDemo; 2 3 import java.io.BufferedReader; 4 5 public class UploadTextClient { 6 7 /** 8 * @param args 9 * @throws IOException 10 * @throws UnknownHostException 11 */ 12 public static void main(String[] args) throws UnknownHostException, 13 IOException { 14 15 Socket s = new Socket("192.168.2.103", 10005); 16 BufferedReader bufr = new BufferedReader(new FileReader("client.txt")); 17 PrintWriter out = new PrintWriter(s.getOutputStream(), true); 18 String line = null; 19 while ((line = bufr.readLine()) != null) { 20 out.println(line); 21 22 } 23 s.shutdownOutput(); 24 BufferedReader bufIn = new BufferedReader(new InputStreamReader( 25 s.getInputStream())); 26 String str = bufIn.readLine(); 27 System.out.println(str); 28 bufr.close(); 29 s.close(); 30 31 } 32 33 }
服务端:
1 package WebProgramingDemo; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.io.PrintWriter; 9 import java.net.ServerSocket; 10 import java.net.Socket; 11 12 public class UploadTextServer { 13 14 /** 15 * @param args 16 * @throws IOException 17 */ 18 public static void main(String[] args) throws IOException { 19 20 ServerSocket ss = new ServerSocket(10005); 21 Socket s = ss.accept(); 22 System.out.println(s.getInetAddress().getHostAddress() 23 + ".....connected"); 24 25 BufferedReader bufIn = new BufferedReader(new InputStreamReader( 26 s.getInputStream())); 27 BufferedWriter bufw = new BufferedWriter(new FileWriter("server.txt")); 28 String line = null; 29 while ((line = bufIn.readLine()) != null) { 30 bufw.write(line); 31 bufw.newLine(); 32 bufw.flush(); 33 } 34 PrintWriter out = new PrintWriter(s.getOutputStream(), true); 35 out.println("上传成功"); 36 bufw.close(); 37 s.close(); 38 ss.close(); 39 } 40 41 }