A very important job of a Web application is to transfer data. The process of transferring data varies depending on which "vehicle" is used, but the way it is transmitted is the same: it is transmitted in bytecode. The process and manner in which the Java Development Network program transmits data is abstracted, we do not need to pay attention to the underlying interface, only need to use the Java API or other network framework to achieve the purpose of data transmission. Both the sending and receiving data are byte codes.
Socket network Programming I'm not going to be more verbose here, I'm comparing the down-blocking IO (OIO) and non-blocking IO (NIO) with two simple examples.
In Oio, each thread can handle only one channel, which is bound to the channel. That is, when the client sends the request, it must have a response on the server before sending the next request. So all requests at this time will be synchronized on the server.
In NiO, each thread can handle multiple channel. In other words, the client sends the request without waiting for a response from the server to send the next request, so that for all request actions it will be asynchronously on the server, and the requested link is like a request queue, and all actions will not be synchronized here.
You may have worked with a network interface provided by Java, and it is difficult to switch from blocking to non-blocking, because there is a big difference between blocking IO and the APIs used by nonblocking IO. It takes a lot of effort and time to refactor the code when we want to switch the transmission mode.
Let's look at the socket server for a traditional blocking IO transmission:
1 /**2 * Traditional blocking IO (OIO), raw socket3 * 4 * <p>Title:PlainOioServer</p>5 * @authorWyx6 * @date 2016-6-15 pm 1:36:047 */8 Public classPlainoioserver {9 Public voidServerintPortthrowsexception{Ten //bind server to Port One FinalServerSocket socket =NewServerSocket (port); A while(true){ - //Accept Connection - FinalSocket Clientsocket =socket.accept (); theSYSTEM.OUT.PRINTLN ("Accepted connection form" +clientsocket); - //create new thread to handle connection - NewThread (NewRunnable () { - + @Override - Public voidrun () { + OutputStream out; A Try { atout =Clientsocket.getoutputstream (); - //write message to connected client -Out.write ("hi!\r\n". GetBytes (Charset.forname ("UTF-8")))); - Out.flush (); - //close connection once message written and flushed - clientsocket.close (); in}Catch(IOException e) { - e.printstacktrace (); to } + } -}). Start ();//start thread to begin handling the } * } $}
The above method is very concise, but this blocking mode in the case of large connections will have serious problems, such as: Client connection timeout, server response to severe delay, etc. To solve this problem, we can use an asynchronous network to handle all concurrent connections, but the problem is that the NIO and Oio APIs are completely different, so a Web application developed with OIO wants to use NIO refactoring code almost to re-develop.
The following code is an example of using Java NIO implementations:
1 /**2 * Traditional non-blocking IO (NIO), raw socket3 * 4 * <p>Title:PlainNioServer</p>5 * @authorWyx6 * @date 2016-6-15 pm 1:46:097 */8 Public classPlainnioserver {9 Public voidServerintPortthrowsexception{TenSystem.out.println ("Listening for connections on port" +port); One //Open selector that handles channels ASelector Selector =Selector.open (); - //Open Serversocketchannel -Serversocketchannel Serverchannel =Serversocketchannel.open (); the //Get ServerSocket -ServerSocket ServerSocket =Serverchannel.socket (); - //bind server to Port -Serversocket.bind (Newinetsocketaddress (port)); + //set to Non-blocking -Serverchannel.configureblocking (false); + //register ServerSocket to selector and specify than it's interested in new accepted clients A Serverchannel.register (selector, selectionkey.op_accept); at FinalBytebuffer msg = Bytebuffer.wrap ("hi!\r\n". GetBytes ()); - while(true){ - //Wait for the new events that is ready for the process. This would block until something happens - intn =Selector.select (); - if(N > 0){ - //obtain all Selectionkey instances that received enents inIterator<selectionkey> iter =Selector.selectedkeys (). iterator (); - while(Iter.hasnext ()) { toSelectionkey key =Iter.next (); + Iter.remove (); - //Check If event is because new client ready to get accepted the if(Key.isacceptable ()) { *Serversocketchannel Server =(Serversocketchannel) Key.channel (); $Socketchannel client =server.accept ();Panax NotoginsengSYSTEM.OUT.PRINTLN ("Accepted connection from" +client); -Client.configureblocking (false); the //Accept Client and register it to Seletor + Client.register (selector, Selectionkey.op_write, msg.duplicate ()); A } the + //Check if event was because socket are ready to write data - if(Key.iswritable ()) { $Socketchannel client =(Socketchannel) Key.channel (); $Bytebuffer buff =(Bytebuffer) key.attachment (); - //Write date to connected client - while(Buff.hasremaining ()) { the if(Client.write (buff) = = 0){ - Break;Wuyi } the } - client.close (); Wu } - } About } $ } - } -}
As you can see, the code is completely different, even when the functionality they implement is the same. Depending on the different needs of different implementation methods, of course, can also directly select the popular Network Transmission framework framework, such as: Netty. To facilitate later maintenance.
Network programming sockets for blocking and non-blocking IO