Java Network Programming-synchronous blocking IO Model __ algorithm

Source: Internet
Author: User
Tags message queue readline

Because the project needs to use Java to develop a background server program, C + + programmers will learn java. Blog content is used to record my learning process. Several network IO models under Unix/linux have been mentioned in previous blogs, but most of them are system calls under Unix/linux.
Most of the blog content from the network information and books "Netty authoritative guide", reproduced please indicate the source http://blog.csdn.net/Robin__Chou/article/details/54378934, thank you.

If you want to know unix/linux under the network IO Model can see the following several related blogs, which are mostly code snippets, the original rational explanation is relatively few.
1.unix/linux of 5 I/O models
2. Multi-Process Concurrent server
3. Multi-threaded Concurrent server
Select for 4.IO multiplexing
The poll of 5.IO Multiplexing
The Epoll of 6.IO multiplexing
Java as a Cross-platform language, of course, will support the above several IO models. In the previous version of JDK1.4, Java support for IO was not as good. It was not until JDK1.4 released that Java began to support non-blocking IO, and this version began to gradually use Java to develop High-performance servers. Even now there is a good open source framework such as Netty,mina. 1. Synchronous Blocking IO Programming

The server side of the synchronous blocking IO model always has a "predecessor" connection responsible for and access to incoming clients. When a client is plugged in, a thread is created to interact with the client, and the main thread continues back to the accept blocking state.
The Java program's socket programming is much more convenient than using C + + development. The following example of a time server program, sample program design ideas on the source of the Netty Authority Guide. The running process of the time server is when the client connects to the server, sends the time query command to the server, and the server receives the command to send back the current times to the client . The procedure is as follows:

Import java.io.IOException;
Import Java.net.ServerSocket;
Import Java.net.Socket;
 * * * The problem with the Bio model is that each client is connected, the server needs to create a thread to handle the client link * A thread can only handle one client connection, and for high-performance, high concurrent access scenarios are difficult to satisfy.                                            * */public class Timeserver {public static void main (string[] args) {int port = 8080;
        The listener port number is 8080 serversocket server = null;
            try {server = new ServerSocket (port);
            SYSTEM.OUT.PRINTLN ("Time Server listening Port:" + port);

            Socket socket = NULL;                           while (true) {socket = server.accept (); ACCECPT blocking waiting for a connection//having a client connection comes in to create a processing thread that is responsible for interacting with the client new thread (new Timeserverhandler (socket)). Star
            T ();
        }}catch (Exception e) {e.printstacktrace (); }finally {if (server!= null) {System.out.println ("server-side shutdown.")
                ");
                try {server.close (); catch (IoexceptiOn e) {e.printstacktrace ();
            } server = null; }
        }
    }
}

The thread that handles the client can be written as:

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;

Import Java.net.Socket;                      public class Timeserverhandler implements Runnable {private socket socket;
    Interaction with Client socket public Timeserverhandler (socket socket) {//constructor, incoming 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 ();
                Read the message sent by the client if (BODY = = null)//Empty message, then turn off server end-end break;

                SYSTEM.OUT.PRINTLN ("Server-side received message:" + body); * * This everywhereThe client request */if ("QUERY time". Equalsignorecase ()) {currenttime = new
                Java.util.Date (System.currenttimemillis ()). ToString ();
                }else{currenttime = "Unrecognized command";
            } out.println (CurrentTime);
                    {Exception e) {//Close accept stream if (in!= null) {try {
                In.close ();
                catch (IOException E1) {e1.printstacktrace ();
                }///Turn off Send stream if (out!= null) {out.close ();
            out = null; }//Close socket if (this.socket!= null) {try {This.socket.clos
                E ();
                catch (IOException E1) {e1.printstacktrace ();
            } this.socket = null; }
        }
    }
}

A

Client program is simpler when a connection is established and a query time command is sent.

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;


Import Java.net.Socket;
        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"); SYSTEM.OUT.PRINTLN ("Successfully send command to server side.")     
            ");                    String resp = In.readline ();
        Read server-side return information System.out.println ("Current time:" + resp);
        catch (Exception e) {e.printstacktrace ();
                Finally {//turn off output stream if (out!= null) {out.close ();
            out = null; //close input data stream
            if (in!= null) {try {in.close ();
                catch (IOException e) {e.printstacktrace ();
            } in = null;
                //Close the socket connection if (socket!= null) {try {socket.close ();
                catch (IOException e) {e.printstacktrace ();
            socket = NULL; }
        }
    }
}
Program Analysis

Synchronous blocking IO Creates a thread to interact with the client when each client connects, and we know that each thread is a resource, and that the process of creating the thread is also to occupy resources. Therefore, it is unreasonable to use synchronous blocking IO for a large number of user connections for server-side programming. This model is also difficult to meet the high performance multiple concurrent access applications. 2. Synchronous blocking IO Programming with thread pool optimization

In order to solve the problem that a client in the synchronous blocking model needs to create a thread to interact with, people optimize it, and the background through a thread pool to handle the solution access of multiple clients.
The difference is that after the client is connected, instead of creating a thread to interact with, it simply throws the client's interaction task to the thread pool to complete. The JDK thread pool maintains a message queue and some active threads to complete the tasks in Message Queuing. The thread pool is the size of the message queue and the maximum number of threads that can be set, so the resources in this way are controllable compared to the previous situation, and do not cause excessive client connections and cause server-side resource depletion.
The same time server as a case, from the code can be seen, in fact, the process is roughly the same, the difference is one in the creation of the thread for client interaction, and the other is to create a thread pool, the client connected directly to the thread pool to deal with.

Import java.io.IOException;
Import Java.net.ServerSocket;

Import Java.net.Socket;


Import Com.phei.netty.bio.TimeServerHandler;                                                
        public class Timeserver {public static void main (string[] args) {//Listener port number is 8080 int port = 8080;
        ServerSocket server = null;
            try {server = new ServerSocket (port);
            SYSTEM.OUT.PRINTLN ("Time Server listening Port:" + port);
            Socket socket = NULL;          Timeserverhandlerexecutepool singleexecutor = new Timeserverhandlerexecutepool (50, 10000);
                Create IO Task thread pool while (true) {socket = server.accept ();
            Singleexecutor.execute (new Timeserverhandler (socket));
        }}catch (Exception e) {e.printstacktrace (); }finally {if (server!= null) {System.out.println ("server-side shutdown.")
                ");
        try {server.close ();        catch (IOException e) {e.printstacktrace ();
            } server = null; }
        }
    }
}
Import Java.util.concurrent.ArrayBlockingQueue;
Import Java.util.concurrent.ExecutorService;
Import Java.util.concurrent.ThreadPoolExecutor;
Import Java.util.concurrent.TimeUnit;


public class Timeserverhandlerexecutepool {

    private executorservice executor;

    Public Timeserverhandlerexecutepool (int maxpoolsize, int queuesize) {
        executor = new Threadpoolexecutor ( Runtime.getruntime (). Availableprocessors (),
                maxpoolsize, 120L, Timeunit.seconds,
                new Arrayblockingqueue <Runnable> (queuesize));
    }

    public void execute (Runnable task) {
        Executor.execute (Task);
    }
}

The processing of a single thread in the thread pool is the same as the handler of the synchronous blocking IO model. The client is not any different. Synchronous blocking IO Programming with thread pool optimization solves the problem of creating threads in the above, because of the introduction of a message queue, if the number of connections once a large amount of time will cause the message delay, if some of the client's network is not smooth, other clients can not get a timely response. and client messages are rejected directly after the queue is full. 3. PostScript

According to the Forum, blog and so on in recent time to look at, the use of Java to develop a background server of a few cases, even the real-time requirements of the game industry also has the use of Java Development Background server case. Mobile app apps Use the Java Development Server in the background more. There are also cases used in the Internet of things, especially smart homes that often use custom communication protocols. Analysis of the use of the principle of no more than two points: easy to use, easy to develop simple maintenance, high reliability

In particular, using open source frameworks such as Netty,mina allows development to focus on the business without being bothered by cumbersome technical details.

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.