packagepseudoasynchronous;importjava.io.IOException;importjava.net.ServerSocket;importjava.net.Socket;publicclassTimeServer{publicstaticvoidmain(String[] args)throwsIOException{int port =8081;if(args !=null&& args.length >0){try{
port =Integer.valueOf(args[0]);}catch(NumberFormatException e){}}ServerSocket server =null;try{
server =newServerSocket(port);System.out.println("The time server is start in port : "+ port);Socket socket =null;TimeServerHandlerExecutePool singleExecutor =newTimeServerHandlerExecutePool(50,10000);// 创建I/O任务线程池while(true){
socket = server.accept();
singleExecutor.execute(newTimeServerHandler(socket));}}finally{if(server !=null){System.out.println("The time server close");
server.close();
server =null;}}}}
TimeServerHandler代码
packagepseudoasynchronous;importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;publicclassTimeServerHandlerimplementsRunnable{privateSocket socket;publicTimeServerHandler(Socket socket){this.socket = socket;}publicvoidrun(){BufferedReader in =null;PrintWriter out =null;try{
in =newBufferedReader(newInputStreamReader(this.socket.getInputStream()));
out =newPrintWriter(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)?newjava.util.Date(System.currentTimeMillis()).toString():"BAD ORDER";
out.println(currentTime);}}catch(Exception e){if(in !=null){try{
in.close();}catch(Exception e2){
e2.printStackTrace();}}if(out !=null){
out.close();
out =null;}if(this.socket !=null){try{this.socket.close();}catch(Exception e2){
e2.printStackTrace();}this.socket =null;}}}}
TimeClient代码
packagepseudoasynchronous;importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;publicclassTimeClient{publicstaticvoidmain(String[] args){int port =8081;if(args !=null&& args.length >0){try{
port =Integer.valueOf(args[0]);}catch(NumberFormatException e){
e.printStackTrace();}}Socket socket =null;BufferedReader in =null;PrintWriter out =null;try{
socket =newSocket("127.0.0.1", port);
in =newBufferedReader(newInputStreamReader(socket.getInputStream()));
out =newPrintWriter(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){}finally{if(out !=null){
out.close();
out =null;}if(in !=null){try{
in.close();}catch(Exception e){
e.printStackTrace();}
in =null;}if(socket !=null){try{
socket.close();}catch(Exception e){
e.printStackTrace();}
socket =null;}}}}
TimeServer代码package pseudoasynchronous;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class TimeServer { public static void main(String[] args) throws IOException { int port = 8081; if (args != null &&