基本模型
代码:
客户端
1 package bhz.bio; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.io.PrintWriter; 7 import java.net.Socket; 8 9 public class Client {10 11 final static String ADDRESS = "127.0.0.1";12 final static int PORT = 8765;13 14 public static void main(String[] args) {15 16 Socket socket = null;17 BufferedReader in = null;18 PrintWriter out = null;19 20 try {21 socket = new Socket(ADDRESS, PORT);22 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));23 out = new PrintWriter(socket.getOutputStream(), true);24 25 //向服务器端发送数据26 out.println("接收到客户端的请求数据...");27 out.println("接收到客户端的请求数据1111...");28 String response = in.readLine();29 System.out.println("Client: " + response);30 31 } catch (Exception e) {32 e.printStackTrace();33 } finally {34 if(in != null){35 try {36 in.close();37 } catch (IOException e) {38 e.printStackTrace();39 }40 }41 if(out != null){42 try {43 out.close();44 } catch (Exception e) {45 e.printStackTrace();46 }47 }48 if(socket != null){49 try {50 socket.close();51 } catch (IOException e) {52 e.printStackTrace();53 }54 }55 socket = null;56 }57 }58 }
服务端
1 package bhz.bio; 2 3 import java.io.IOException; 4 import java.net.ServerSocket; 5 import java.net.Socket; 6 7 8 public class Server { 9 10 final static int PROT = 8765;11 12 public static void main(String[] args) {13 14 ServerSocket server = null;15 try {16 server = new ServerSocket(PROT);17 System.out.println(" server start .. ");18 //进行阻塞19 Socket socket = server.accept();20 //新建一个线程执行客户端的任务21 new Thread(new ServerHandler(socket)).start();22 23 } catch (Exception e) {24 e.printStackTrace();25 } finally {26 if(server != null){27 try {28 server.close();29 } catch (IOException e) {30 e.printStackTrace();31 }32 }33 server = null;34 }35 36 37 38 }39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 }
处理类
package bhz.bio;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;public class ServerHandler implements Runnable{ private Socket socket ; public ServerHandler(Socket socket){ this.socket = socket; } @Override public void run() { BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); out = new PrintWriter(this.socket.getOutputStream(), true); String body = null; while(true){ body = in.readLine(); if(body == null) break; System.out.println("Server :" + body); out.println("服务器端回送响的应数据."); } } catch (Exception e) { e.printStackTrace(); } finally { if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if(out != null){ try { out.close(); } catch (Exception e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } socket = null; } }}