同步阻塞式io通訊示例
阿新 • • 發佈:2019-01-12
伺服器類
package com.bai.test; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws IOException { int port = 8000; ServerSocket server = null; try { server = new ServerSocket(port); System.out.println("伺服器啟動"); Socket socket = null; while(true){ socket = server.accept(); new Thread(new TimeServerHandler(socket)).start(); } } finally { if(server != null){ System.out.println("關閉服務"); server.close(); server = null; } } } }
任務執行緒類
package com.bai.test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Date; public class TimeServerHandler implements Runnable { private Socket socket; public TimeServerHandler(Socket socket) { this.socket = socket; } @Override public void run() { BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(),true); String currentTime = null; String body = null; while(true){ body = in.readLine(); if(body == null){ break; } System.out.println("伺服器功能:"+body); currentTime = "查詢".equals(body)?new Date(System.currentTimeMillis()).toString():"無服務"; out.println(currentTime); } } catch (Exception e) { if(in != null){ try { in.close(); } catch (Exception e2) { e2.printStackTrace(); } } if(out != null){ try { out.close(); out = null; } catch (Exception e2) { e2.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (Exception e2) { e2.printStackTrace(); } socket = null; } } } }
客戶端程式碼
package com.bai.test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Cilent { public static void main(String[] args) { int port = 8000; Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket("127.0.0.1", port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(),true); out.println("查詢時間"); System.out.println("傳送請求"); String resp = in.readLine(); System.out.println("現在是:"+resp); } catch (Exception e) { e.printStackTrace(); } finally{ if(in != null){ try { in.close(); } catch (Exception e2) { e2.printStackTrace(); } } if(out != null){ try { out.close(); out = null; } catch (Exception e2) { e2.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (Exception e2) { e2.printStackTrace(); } socket = null; } } } }