The asynchronous input/output mechanism means that the input/output processing does not have to wait until the input/output processing is complete. Therefore, asynchronous synonyms are non-blocking (none blocking ).
On the Internet, many netizens use a very popular metaphor to thoroughly explain synchronization and Asynchronization.
For example: Normal B/S mode (synchronous) Ajax technology (asynchronous)
Synchronization: submit a request, wait for the server to process, and return the result. The client browser cannot do anything during this period.
Asynchronous: requests are triggered through events-> server processing (this is what the browser can do)-> processing is complete
Synchronization means that you ask me to go to dinner. When I hear it, I will go to dinner with you. If I don't hear it, you will not stop calling until I tell you to hear it.
Asynchronous mode means that you call me and then eat on your own. After receiving the message, I may leave immediately or wait until I get off work.
Therefore, if I want to invite you to dinner, I will use the synchronous method. If I want to invite you to dinner, I will use the asynchronous method, so that you can save money.
Take communication as an Example
Synchronization: send a request, wait for the return, and then send the next request
Asynchronous: send a request. You can send the next request at any time without waiting for the response.
Concurrency: send multiple requests at the same time
Next, let's take a lookJavaArticles about asynchronous applications
Write a socket process communication program using an asynchronous input/output stream
Added the application interface package for implementing asynchronous input/output Mechanism in Merlin: Java. niO (a new input/output package that defines many basic types of buffer), Java. NIO. channels (channels and selectors, used for asynchronous input and output), Java. NIO. charset (character encoding and decoding ). Channel first registers events of interest in the selector. when an event occurs, the selectionkey is used to notify the registered channel. Then, the channel packages the information to be processed, encodes and decodes it, and controls the input and output.
Channel introduction:
Here we mainly introduce serversocketchannel and socketchannel. they are all selectable (selectable) channels, which can work in both synchronous and asynchronous modes (Note: The options here do not mean that you can select two working modes, you can register events that you are interested in ). You can use channel. configureblocking (Boolean) to set the working mode. Compared with APIs of previous versions, serversocketchannel is equivalent to serversocket
(Serversocketchannel encapsulates serversocket), while socketchannel is equivalent to socket (socketchannel encapsulates socket ). When the channel is working in synchronization mode,ProgrammingThe method is similar to the previous one. Here we mainly introduce the asynchronous working method.
The asynchronous input/output mechanism means that the input/output processing does not have to wait until the input/output processing is complete. Therefore, asynchronous synonyms are non-blocking (none blocking ). On the server side, serversocketchannel returns an instance of serverchlorophyll through the static function open. Then, this channel calls serverchlorophyll. socket (). BIND () to a port on the server, and call register (selector Sel, selectionkey. op_accept) registers the op_accept event to a selector (serversocketchannel can only register the op_accept event ). When a customer requests a connection, the selector notifies the channel that a customer connection request is in place to control the input and output. On the client, after registering events that interest you (op_connect, op_read, and op_write combinations), The clientchlorophyll instance calls. connect
(Inetsocketaddress) connects to the server and then processes it accordingly. Note that the connection here is asynchronous, that is, it will return immediately and continue the subsequent executionCode.
Introduction to selector and selection key:
Selector is used to put events of interest to the channel into the queue, rather than submitting them to the application immediately, and wait for the registered channel to request to process these events by itself. In other words, the selector will report the prepared channel at any time in the FIFO order. So what is the selector reporting? Select key ). The key selection function is to indicate which channel is ready and what to prepare. You may think immediately that it must be an event of interest to the registered channel. Good. For example, for server-side Server Load balancer, you can call key. isacceptable () to notify the Server Load balancer of client connection requests. The corresponding functions include: selectionkey. isreadable (), selectionkey. iswritable (). Generally, poll events of interest in a loop (refer to the following code for details ). If there is no channel registered event in the selector, calling selector. Select () will be blocked until an event occurs. In addition, you can call selectnow () or select (long
Timeout ). The former returns immediately, and 0 is returned if there is no event; the latter returns after the timeout time. A selector can be registered with up to 63 channels at the same time.
Application instance:
The following is a list of client/server instance programs implemented using the asynchronous input/output mechanism. Program 1 (limited by space, only server implementation is provided. You can refer to the implementation of client code):
- Public class nblockingserver {
- Int Port = 8000;
- Int buffer size = 1024;
- Selector selector = NULL;
- Serversocketchannel serverchannel = NULL;
- Hashmap clientchannelmap = NULL; // used to store the socket and channel corresponding to each customer connection
- Public nblockingserver (INT port ){
- This. clientchannelmap = new hashmap ();
- This. Port = port;
- }
- Public void initialize () throws ioexception {
- // Initialize and instantiate a selector. A server can select a channel.
- This. selector = selector. open ();
- This. serverchannel = serversocketchannel. open ();
- This. serverchannel. configureblocking (false );
- Inetaddress localhost = inetaddress. getlocalhost ();
- Inetsocketaddress ISA = new inetsocketaddress (localhost, this. Port );
- This. serverchannel. socket (). BIND (ISA); // bind the socket to a port available on the server.
- }
- // Release resources at the end
- Public void finalize () throws ioexception {
- This. serverchannel. Close ();
- This. selector. Close ();
- }
- // Decodes the information that is read into the byte Buffer
- Public String decode (bytebuffer) throws
- Charactercodingexception {
- Charset = charset. forname ("ISO-8859-1 ");
- Charsetdecoder decoder = charset. newdecoder ();
- Charbuffer = decoder. Decode (bytebuffer );
- String result = charbuffer. tostring ();
- Return result;
- }
- // Listener port. Perform corresponding operations when the channel is ready
- Public void portlistening () throws ioexception, interruptedexception {
- // Register the op_accept event through the server Channel
- Selectionkey acceptkey = This. serverchannel. Register (this. selector,
- Selectionkey. op_accept );
- // When a registered event occurs, the return value of select () is greater than 0.
- While (acceptkey. selector (). Select ()> 0 ){
- System. Out. println ("event happened ");
- // Obtain all the available selection keys
- Set readykeys = This. selector. selectedkeys ();
- // Use the iterator to round the selection key
- Iterator I = readykeys. iterator ();
- While (I. hasnext ()){
- Selectionkey key = (selectionkey) I. Next ();
- I. Remove (); // Delete the selection key to be processed.
- If (key. isacceptable () {// If a client connection request exists
- System. Out. println ("more client connect in! ");
- Serversocketchannel nextready =
- (Serversocketchannel) Key. Channel ();
- // Obtain the client socket
- Socket S = nextready. Accept ();
- // Set the corresponding channel to asynchronous mode and register events of interest
- S. getchannel (). configureblocking (false );
- Selectionkey readwritekey =
- S. getchannel (). Register (this. selector,
- Selectionkey. op_read | selectionkey. op_write );
- // Associate the registered event with the socket
- Readwritekey. Attach (s );
- // Store the currently established client socket and corresponding channel in the hash table // clientchannelmap
- This. clientchannelmap. Put (s, new
- Clientchinstance (S. getchannel ()));
- }
- Else if (key. isreadable () {// if it is a channel read readiness event
- System. Out. println ("readable ");
- // Obtain the channel and socket corresponding to the selection key
- Selectablechannel nextready =
- (Selectablechannel) Key. Channel ();
- Socket socket = (socket) Key. Attachment ();
- // Process the event. The handling method is encapsulated in the clientchinstance class.
- This. readfromchannel (socket. getchannel (),
- (Clientchinstance)
- This. clientchannelmap. Get (socket ));
- }
- Else if (key. iswritable () {// if it is a channel write preparation event
- System. Out. println ("writeable ");
- // Obtain the socket post-processing method, same as above
- Socket socket = (socket) Key. Attachment ();
- Socketchannel channel = (socketchannel)
- Socket. getchannel ();
- This. writetochannel (Channel, "this is from server! ");
- }
- }
- }
- }
- // Write operations on the Channel
- Public void writetochannel (socketchannel channel, string message)
- Throws ioexception {
- Bytebuffer Buf = bytebuffer. Wrap (message. getbytes ());
- Int nbytes = channel. Write (BUF );
- }
- // Read operations on the Channel
- Public void readfromchannel (socketchannel channel, clientchinstance clientinstance)
- Throws ioexception, interruptedexception {
- Bytebuffer = bytebuffer. Allocate (buffersize );
- Int nbytes = channel. Read (bytebuffer );
- Bytebuffer. Flip ();
- String result = This. Decode (bytebuffer );
- // Close the channel when the client issues the "@ exit" command
- If (result. indexof ("@ exit")> = 0 ){
- Channel. Close ();
- }
- Else {
- Clientinstance. append (result. tostring ());
- // After reading a row, perform the corresponding operation
- If (result. indexof ("\ n")> = 0 ){
- System. Out. println ("client input" + result );
- Clientinstance.exe cute ();
- }
- }
- }
- // This class encapsulates how to perform operations on the client channel. The specific implementation can be done by reloading the execute () method.
- Public class clientchinstance {
- Socketchannel channel;
- Stringbuffer buffer = new stringbuffer ();
- Public clientchinstance (socketchannel channel ){
- This. Channel = channel;
- }
- Public void execute () throws ioexception {
- String message = "This Is response after reading from Channel! ";
- Writetochannel (this. Channel, message );
- Buffer = new stringbuffer ();
- }
- // When a row does not end, place the current word seek at the end of the buffer
- Public void append (string values ){
- Buffer. append (values );
- }
- }
- // Main program
- Public static void main (string [] ARGs ){
- Nblockingserver nbserver = new nblockingserver (8000 );
- Try {
- Nbserver. initialize ();
- } Catch (exception e ){
- E. printstacktrace ();
- System. Exit (-1 );
- }
- Try {
- Nbserver. portlistening ();
- }
- Catch (exception e ){
- E. printstacktrace ();
- }
- }
- }
Summary:
From the above section, we can see that the client has completed the customer/Server mode for multiple customers without introducing redundant threads. The callback mode is used in this program, which should be visible to the readers. Note that do not mix the original input/output package with the newly added input/output package. For some reason, these two packages are not compatible. When using channels, use buffering to control input and output. In Windows and j2se1.4, use Telnet.TestSuccessful.
The preceding code is transferred from http://space.itpub.net/17074730/viewspace-563262 .. This is really good ..