Using asynchronous input-output stream to write socket process communication

Source: Internet
Author: User
Tags bind socket

Synchronous? Introduction of asynchronous input-output mechanism

Before Merlin, it would be tedious to write a socket program. Because the input and output must be synchronized. In this way, for multiple client/server mode, it is necessary to use multithreading. That is, each connected customer is assigned a thread to process the input and output. It is conceivable that the problems brought about. Programmers have to do a lot of coding and testing to avoid deadlocks, line Cheng, and so on. A lot of people are complaining about why the asynchronous input-output mechanism is not introduced in Java. The more official explanation is that any application interface must be introduced with any operating platform. Java is cross-platform. The operating platform that supports the asynchronous input and output mechanism is clearly impossible to be all. Since the Java 2 platform, j2se,j2me,j2ee three different types of application interfaces have been isolated to suit different application development. The Java standard makers are aware of this problem, and the operating platform that supports asynchronous input and output mechanisms is dominant in today's operating platform. As a result, the asynchronous input-output mechanism was introduced in the fifth release of the JDK (J2SE).

In the previous socket process communication program design, the general client and server-side program design is as follows:

Server side:

  //服务器 端监听线程
  while (true) {
         .............
        Socket clientSocket;
         clientSocket = socket.accept(); //取得客户请求Socket,如果没 有//客户请求连接,线程在此处阻塞
        //用取得的Socket 构造输入输出流
        PrintStream os = new PrintStream (new
        BufferedOutputStream (clientSocket.getOutputStream(),
        1024), false);
        BufferedReader is = new BufferedReader (new
        InputStreamReader (clientSocket.getInputStream()));
        //创建客户会话 线程,进行输入输出控制,为同步机制
        new ClientSession();
        .......
         }

Client:

 ............
  clientSocket = new Socket(HOSTNAME, LISTENPORT);//连接服务器套接字
  //用取得的 Socket构造输入输出流
  PrintStream os = new PrintStream(new
        BufferedOutputStream(clientSocket.getOutputStream (),
        1024), false);
         BufferedReader is = new BufferedReader(new
         InputStreamReader(clientSocket.getInputStream()));
  //进行输入 输出控制
  .......

The above code snippet only uses the synchronization mechanism to write the socket process communication frame, actually needs to consider the question to be more complex (the interested reader may refer to my article "The Internet Real Time communication system design and the realization"). This frame is listed only for comparison with the socket process communication implemented using the asynchronous mechanism. The program that uses asynchronous mechanisms is described below.

Writing a socket process communication program with an asynchronous input/output stream

The application interface package used to implement the asynchronous input/output mechanism was added to Merlin: Java.nio (new input and output package, defined many basic type buffers (buffer), java.nio.channels (channel and selector, etc. for asynchronous input and output), Java.nio.charset (encoding and decoding of characters). The channel (Channel) first registers an event of interest in the selector (Selector), and when the corresponding event occurs, the selector notifies the registered channel by selecting the Key (Selectionkey). Then the channel will need to process the information, through buffering (buffer) packaging, encoding/decoding, complete the input and output control.

Channel Introduction:

Here is a brief introduction to Serversocketchannel and Socketchannel. They are both optional (selectable) channels that work in both synchronous and asynchronous ways (note that the alternative here is not to choose between two ways of working, Instead, it means that you can have a choice of registering events of interest to yourself. You can use Channel.configureblocking (Boolean) to set how it works. Compared to previous versions of the API, Serversocketchannel is equivalent to ServerSocket (Serversocketchannel encapsulates ServerSocket), The Socketchannel is equivalent to the socket (Socketchannel encapsulates the socket). When the channel works in sync mode, the programming method is similar to the previous, here mainly introduces the asynchronous work way.

The so-called asynchronous input and output mechanism, refers to the input and output processing, do not have to wait until the input and output processing completed before returning. So asynchronous synonyms are non-blocking (None Blocking). On the server side, Serversocketchannel returns an instance serverchl through the static function open (). The channel then invokes Serverchl.socket (). bind () bind to a port on the server and call register (Selector sel, selectionkey.op_accept) for registration OP_ Accept event to a selector (Serversocketchannel can only register op_accept events). When a client requests a connection, the selector notifies the channel that there is a client connection request, and the corresponding input/output control is available; At the client, the CLIENTCHL instance registers an event of interest to itself (can be a combination of op_connect,op_read,op_write), Call Clientchl.connect (inetsocketaddress) to connect to the server and handle it accordingly. Note that the connection here is asynchronous, that is, it returns immediately and continues to execute the following code.

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.