Java IO Programming Full Solution (ii)--traditional bio programming

Source: Internet
Author: User
Tags message queue readline

Previous: Java IO programming Full solution (i)--java I/O evolution path

The basic model of network programming is the Client/server model, that is, two processes to communicate with each other, where the server provides location information (bound IP address and listening port), the client through the connection operation to the server to listen to the address to initiate a connection request, through three handshake to establish a connection, If the connection is successful, both parties can communicate over a network socket (socket).

In the development of traditional synchronous blocking model, ServerSocket is responsible for binding IP address, initiating the listening port, and the socket is responsible for initiating the connection operation. After the connection is successful, both sides synchronize the blocking communication through the input and output streams.

Take the classic time server (Timeserver) as an example to review and familiarize yourself with the next bio programming through code analysis.

1. Bio Communication Model Diagram

such as bio's server-side communication model: using the Bio communication model of the server, usually by a separate acceptor thread is responsible for listening to the client connection, it receives a client connection request after each client to create a new thread for the link processing, after processing is completed, return to the client by the output stream , the thread is destroyed. This is typically a request-to-answer communication model.

Figure 1 Synchronous blocking I/O server-side communication model (one client thread)

The biggest problem of the model is the lack of elastic scalability, when the client concurrent access increases, the number of threads on the server and the number of client concurrent access is proportional to 1:1, the hesitant thread is a very valuable system resource of Java Virtual Machine, when the number of threads expands, the performance of the system will drop sharply, As the number of concurrent accesses continues to increase, problems such as thread stack Overflow, creation of a new thread failure, and eventually a process outage or zombie, cannot be serviced externally.

2. Timeserver for synchronous blocking I/O creation
 PackageJoanna.yan.bio;Importjava.io.IOException;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classTimeserver { Public Static voidMain (string[] args) {intport=9090; if(args!=NULL&&args.length>0){            Try{Port=integer.valueof (args[0]); } Catch(Exception e) {//with default values}} ServerSocket server=NULL; Try{Server=NewServerSocket (port); System.out.println ("The time server is a start in port:" +port); Socket Socket=NULL;  while(true){//listens for client connections through an infinite loopSocket=server.accept ();//If there is no client access, the main thread is blocked on the ServerSocket accept operation.                 NewThread (NewTimeserverhandler (socket)). Start (); }        } Catch(IOException e) {e.printstacktrace (); }finally{            if(server!=NULL) {System.out.println ("The time server close"); Try{server.close (); Server=NULL; } Catch(IOException e) {e.printstacktrace (); }            }        }    }}
 PackageJoanna.yan.bio;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.util.Date; Public classTimeserverhandlerImplementsrunnable{Privatesocket socket;  PublicTimeserverhandler (socket socket) { This. Socket =socket; } @Override Public voidrun () {BufferedReader in=NULL; PrintWriter out=NULL; Try{ in=NewBufferedReader (NewInputStreamReader ( This. Socket.getinputstream ())); out=NewPrintWriter ( 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); //If the request message is the instruction "Query time order" for the queried times, the current system time is obtained. Currenttime= "QUERY time ORDER". Equalsignorecase (body)?NewDate (System.currenttimemillis ()). ToString (): "Bad ORDER";            Out.println (currenttime); }        } Catch(IOException e) {e.printstacktrace (); }finally{            if(in!=NULL){                Try{in.close (); } Catch(IOException e) {e.printstacktrace (); }            }            if(out!=NULL) {out.close (); out=NULL; }            if( This. socket!=NULL){                Try {                     This. Socket.close ();  This. socket=NULL; } Catch(IOException e) {e.printstacktrace (); }            }        }    }}
3. Timeclient for synchronous blocking I/O creation

The client creates through the socket, sends a query time order instruction to the server, reads the response from the service side, prints the result, closes the connection, frees the resource, and the program exits execution.

 PackageJoanna.yan.bio;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.net.UnknownHostException; Public classtimeclient { Public Static voidMain (string[] args) {intport=9090; if(args!=NULL&&args.length>0){            Try{Port=integer.valueof (args[0]); } Catch(Exception e) {//with default values}} 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"); System.out.println ("Send order 2 server succeed."); String resp=In.readline (); System.out.println ("Now is:" +resp); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{            if(out!=NULL) {out.close (); out=NULL; }            if(in!=NULL){                Try{in.close (); } Catch(IOException e) {e.printstacktrace (); } in=NULL; }            if(socket!=NULL){                Try{socket.close (); } Catch(IOException e) {e.printstacktrace (); } Socket=NULL; }        }    }}

We found that the main problem with bio is that whenever a new client requests access, the server must create a new thread to handle the newly accessed client link, and a thread can only struggle with one client connection. In high-performance server applications, there is often a need for concurrent connections to tens of thousands of clients, a model that clearly does not meet high-performance, highly concurrent access scenarios.

In order to improve the one-thread-connection model, a model that implements 1 or more threads to process n clients through a thread pool or message queue has been developed, which is called "pseudo-async" because its underlying communication mechanism still uses synchronous blocking I/O. Later, we will analyze pseudo-asynchronous code to see if pseudo-async can satisfy our demand for high-performance, high-concurrency access.

If this article is helpful to you, please give me a reward!

Java IO Programming Full Solution (ii)--traditional bio programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.