缺点:一个线程只能处理一个客户端连接
服务端:
public class TimeServer { public static void main(String[] args) throws IOException { int port = 8080; ServerSocket server = null; try { server = new ServerSocket(port); System.out.println("The time server is start in port : " + port); Socket socket = null; while (true) { socket = server.accept();//阻塞直到有新的连接 //每监听到一个socket连接就生成一个新的线程来处理 new Thread(new TimeServerHandler(socket)).start(); } } finally { if (server != null) { System.out.println("The time server close"); server.close(); server = null; } } } }
事务处理线程:
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(this.socket.getInputStream())); out = new PrintWriter(this.socket.getOutputStream(), true); String currentTime = null; String body = null; while (true) { body = in.readLine();//阻塞直到有数据读入,或者数据读完或发生异常 if (body == null) break; System.out.println("The time server receive order : " + body); currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date( System.currentTimeMillis()).toString() : "BAD ORDER"; out.println(currentTime);//输出 } } catch (Exception e) { //处理异常 } } }
客户端:
public class TimeClient { public static void main(String[] args) { int port = 8080; 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("QUERY TIME ORDER");//发送请求 System.out.println("Send order 2 server succeed."); String resp = in.readLine();//回复 System.out.println("Now is : " + resp); } catch (Exception e) { e.printStackTrace(); } finally { if (this.socket != null) { try { this.socket.close(); } catch (IOException e1) { e1.printStackTrace(); } this.socket = null; } } } }
时间: 2024-10-26 21:06:22