Disadvantage: A thread can handle only one client connection
Service side:
Public classTimeserver { Public Static voidMain (string[] args)throwsIOException {intPort = 8080; ServerSocket Server=NULL; Try{Server=NewServerSocket (port); System.out.println ("The time server is a start in port:" +port); Socket Socket=NULL; while(true) {Socket= Server.accept ();//block until a new connection is available//each monitor hears a socket connection and generates a new thread to handle NewThread (NewTimeserverhandler (socket)). Start (); } } finally { if(Server! =NULL) {System.out.println ("The time server close"); Server.close (); Server=NULL; } } }}
Transaction thread:
Public classTimeserverhandlerImplementsRunnable {Privatesocket socket; PublicTimeserverhandler (socket socket) { This. Socket =socket; } @Override Public voidrun () {BufferedReader in=NULL; PrintWriter out=NULL; Try { //get input and output streamin =NewBufferedReader (NewInputStreamReader ( This. Socket.getinputstream ())); out=NewPrintWriter ( This. Socket.getoutputstream (),true); String currenttime=NULL; String Body=NULL; while(true) {Body= In.readline ();//block until data is read, or data is read or an exception occurs 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);//Output } } Catch(Exception e) {//Handling Exceptions } }}
Client:
Public classtimeclient { Public Static voidMain (string[] args) {intPort = 8080; Socket Socket=NULL; BufferedReader in=NULL; PrintWriter out=NULL; Try{Socket=NewSocket ("127.0.0.1", Port); Inch=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); out=NewPrintWriter (Socket.getoutputstream (),true); Out.println ("QUERY Time ORDER");//Send Request System.out.println ("Send order 2 server succeed."); String resp=in.readline ();//reply 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; } } }}
Java network communication: synchronous blocking I/O model (BIO)