Introduction to Java IO multiplexing technology

Source: Internet
Author: User

<span style= "FONT-SIZE:18PX;" >package com.winwill.nio;/** * @author qifuguang * @date 15-2-4 pm 2:07 */public class Timeservermain {public    Stati c void Main (string[] args) throws Exception {        //Start time server        new Thread (New Selectortimeserver ()). Start ();}    } </span>


<span style= "FONT-SIZE:18PX;" >package com.winwill.nio;/** * @author qifuguang * @date 15-2-4 pm 2:09 */public class Timeclientmain {public    Stati c void Main (string[] args) throws Exception {        //Create 100 clients to connect to server for        (int i = 0; i <; i++) {            new Thread (New Selectortimeclient (i + 1)). Start ();}}    </span>


<span style= "FONT-SIZE:18PX;" >package Com.winwill.nio;import Java.net.inetsocketaddress;import Java.nio.bytebuffer;import Java.nio.channels.selectionkey;import Java.nio.channels.selector;import Java.nio.channels.ServerSocketChannel; Import Java.nio.channels.socketchannel;import Java.text.simpledateformat;import Java.util.date;import    java.util.iterator;/** * @author Qifuguang * @date 15-2-4 pm 1:21 */public class Selectortimeserver implements Runnable {    private static final String Time_order = "Query time";    Private Selector Selector;    Private Serversocketchannel Serverchannel;    Private volatile Boolean stop = false;     /** * Create selector, create Serversocketchannel, and set to non-blocking mode, register to selector.        * * @throws Exception */Public Selectortimeserver () throws Exception {selector = Selector.open ();        Serverchannel = Serversocketchannel.open ();        Serverchannel.socket (). bind (New inetsocketaddress (8080));        Serverchannel.configureblocking (FALSE);Serverchannel.register (selector, selectionkey.op_accept);     }/** * Polling listener selector. */@Override public void Run () {try {System.out.println ("Time server started!            ");                while (!stop) {selector.select (1000);                iterator<selectionkey> Iterator = Selector.selectedkeys (). Iterator ();                    while (Iterator.hasnext ()) {Selectionkey key = Iterator.next ();                    Iterator.remove ();                Handlekey (key);            }} if (selector! = null) {selector.close ();        }} catch (Exception e) {e.printstacktrace ();     }}/** * Handles events of interest to each selector.     * * @param key poll to get Selectionkey.  */private void Handlekey (Selectionkey key) {try {if (Key.isvalid ()) {//If the connection succeeds if (Key.isacceptable ()) {//Supervisor hears a new client connection Socketchannel accept = ((ServersoCketchannel) Key.channel ()). Accept ();  Establish a connection to the client accept.configureblocking (FALSE); Set the connection as non-blocking mode Accept.register (selector, selectionkey.op_read);                Register the connection to selector System.out.println ("Discover new client connections ..."); } if (Key.isreadable ()) {//monitor heard there is a client sending request Socketchannel Channel = (socketchannel) key.                    Channel ();                    Read request from client Bytebuffer buff = bytebuffer.allocate (1024);                    int size = Channel.read (buff);                        if (Size > 0) {byte[] b = new Byte[size];                        Buff.flip ();                        Buff.get (b);                        String order = new String (b, "UTF-8");                        System.out.println ("Received client command:" + order);                        String content = ""; if (Order.equalsignorecase (Time_order)) {content = new SimpledatEformat ("Yyyy-mm-dd HH:mm:ss"). Format (new Date ());                        } else {content = "command error";                    }//According to the request from the client to make the corresponding action, and return the processing results to the client Dowrite (channel, content);                        } else if (size < 0) {channel.close ();                    Key.cancel ();                    } else {;        }}}} catch (Exception e) {e.printstacktrace ();     }}/** * Sends the specified message to the specified socketchannel.  * * @param SC needs to send a message to which Socketchannel * @param content needs to be sent * @throws Exception */private void        Dowrite (Socketchannel SC, String content) throws Exception {Bytebuffer buffer = bytebuffer.allocate (1024);        Buffer.put (Content.getbytes ("UTF-8"));        Buffer.flip ();        Sc.write (buffer); if (!buffer.hasremaining ()) {System.out.prinTLN ("Send Message to Client:" + content); }}}</span>

<span style= "FONT-SIZE:18PX;" >package Com.winwill.nio;import Java.net.inetsocketaddress;import Java.nio.bytebuffer;import Java.nio.channels.selectionkey;import Java.nio.channels.selector;import Java.nio.channels.socketchannel;import    java.util.iterator;/** * @author Qifuguang * @date 15-2-4 pm 1:21 */public class Selectortimeclient implements Runnable {    private static final String Time_order = "Query time";    Private Socketchannel channel;    Private Selector Selector;    Private volatile Boolean stop = false;    Private Integer index;     /** * Create selector, Socketchannel.     * * @param index client number. * @throws Exception */public selectortimeclient (Integer index) throws Exception {selector = Selector.open (        );        Channel = Socketchannel.open ();        Channel.configureblocking (FALSE);    This.index = index;     }/** * Polls listeners for events that are just interested in selector. */@Override public void Run () {try {System.out.println ("+ Index +" customerEnd-Start! "); First try to connect to the server asynchronously, if the connection is successful, you only need to register the channel to the selector read event,//Read the results returned by the server.            If it is unsuccessful (the client has sent a sync packet to the server, but the server does not return an ACK packet, the physical link has not yet succeeded)//the channel is registered to the Selector connect event, waiting for the ACK packet returned by the server.                if (Channel.connect (new inetsocketaddress (8080))) {Channel.register (selector, selectionkey.op_read);            Dowrite (channel, Time_order);            } else {Channel.register (selector, selectionkey.op_connect);                } while (!stop) {selector.select (1000);                iterator<selectionkey> Iterator = Selector.selectedkeys (). Iterator ();                    while (Iterator.hasnext ()) {Selectionkey key = Iterator.next ();                    Socketchannel sc = (socketchannel) key.channel ();                    Iterator.remove ();                            if (Key.isvalid ()) {if (key.isreadable ()) {//} hears a readable event and reads the processing result returned by the server. Bytebuffer bUff = bytebuffer.allocate (1024);                            int size = Sc.read (buff);                                if (Size > 0) {byte[] b = new Byte[size];                                Buff.flip ();                                Buff.get (b);                                SYSTEM.OUT.PRINTLN ("+ index +" client gets the server return time: "+ new String (b));                            Stop = true;                                } else if (size < 0) {sc.close ();                            Key.cancel ();                            } else {;                            }} if (Key.isconnectable ()) {//monitor the server returned an ACK packet, ready to complete the connection establishment if (Sc.finishconnect ()) {//Call this method to complete the establishment of a physical link connection sc.register (selector, Selectionkey . Op_read);            After establishing the connection, register the listening read event Dowrite (SC, time_order);                } else {system.exit (1);            Otherwise, the program exits}}}}            if (selector! = null) {selector.close ();        }} catch (Exception e) {e.printstacktrace ();     }}/** * Sends the specified message to the specified channel. * * @param channel to which channel to send message * @param content needs to be sent message * @throws Exception */private void Dowrite        (Socketchannel channel, String content) throws Exception {Bytebuffer buff = bytebuffer.allocate (1024);        Buff.put (Content.getbytes ("UTF-8"));        Buff.flip ();        Channel.write (Buff);        if (!buff.hasremaining ()) {System.out.println ("+ Index +" client successfully sends a request to the server: "+ content); }}}</span>



Introduction to Java IO multiplexing technology

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.