http://blog.csdn.net/defonds/article/details/7971259
多個客戶端對應一個服務端的通信的一個小例子。
服務端和客戶端代碼:
public class Server { /** * 監聽的端口 */ public static final int PORT = 12345; public static void main(String[] args) { System.out.println("服務器啟動》》》》》》"); Server server = new Server(); server.init(); } public void init(){ try { ServerSocket serverSocket = new ServerSocket(PORT); while (true){ //一旦有堵塞,表示服務器與客戶端獲得了連接 Socket client = serverSocket.accept(); new HandlerThread(client); } } catch (Exception e) { e.printStackTrace(); } } private class HandlerThread implements Runnable{ private Socket socket; public HandlerThread(Socket socket) { this.socket = socket; new Thread(this).start(); } @Override public void run() { try { //讀取客戶端數據 DataInputStream input = new DataInputStream(socket.getInputStream()); //這里要注意和客戶端輸出流的寫方法對應,否則會拋 EOFException String clientInputStr = input.readUTF(); //處理客戶端發送的數據 System.out.println("客戶端發過來的內容:"+clientInputStr); //想客戶端發送消息 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.println("請輸入:\t"); String outStr = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(outStr); out.close(); input.close(); } catch (IOException e) { System.out.println("服務器異常:"+e.getMessage()); }finally { if (socket != null) { try { socket.close(); } catch (Exception e) { socket = null; System.out.println("服務端 finally 異常:" + e.getMessage()); } } } } } }
public class Client { public static final int PORT = 12345; public static final String IP_ADDR = "localhost"; public static void main(String[] args) { System.out.println("客戶端啟用》》》》》》"); System.out.println("當接收到服務器端字符為 \"OK\" 的時候, 客戶端將終止\n"); while (true){ Socket socket = null; try { //創建一個流套接字並將其連接到指定主機上的指定端口號 socket = new Socket(IP_ADDR,PORT); socket.setSoTimeout(5000); //讀取服務器端數據 DataInputStream input = new DataInputStream(socket.getInputStream()); //向服務器端發送數據 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.print("請輸入: \t"); String str = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(str); String ret = input.readUTF(); System.out.println("服務器端返回過來的是: " + ret); if (ret.endsWith("OK")) { System.out.println("客戶端將關閉連接"); Thread.sleep(500); break; } out.close(); input.close(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }finally { if (socket != null) { try { socket.close(); } catch (IOException e) { socket = null; System.out.println("客戶端 finally 異常:" + e.getMessage()); } } } } } }