Using NIO to realize the principle of non-blocking socket communication

Source: Internet
Author: User

Just learn nio and write your own understanding
in network communication, NIO provides Socketchannel and Serversocketchannel two different socket channels to implement, you can set up blocking and non-blocking two modes, In order to achieve high load high concurrency all adopt non-blocking mode. Channels are two-way and can send and read data on the channel at the same time. NIO uses buffer buffers of the allocated size to realize the data reading and writing operations. The
server uses only one thread to handle all client threads, which requires creating a selector, Register the Serversocketchannel and the socketchannel you want to monitor into the selector (using the Selectablechannel register method, The method returns a key that the channel registers with the selector and is an Selectionkey instance that wraps Selectablechannel and the operations that are of interest to the channel.
Selector, like an observer, constantly gets the return value of the selector Select method, which is the number of selectionkey that are ready to be returned, It then handles (returns the selected Selectionkey collection via the selector Selectedkeys method, and then processes the connection request and reads the data).
Each client has only one socketchannel, and the selector can be monitored after registering the socketchannel with the specified selector. If the return value of the Select method that listens to the selector is greater than 0, the selector has a selectionkey that requires IO processing, and the request and data can be processed after the Socketchannel is obtained.
code to paste a practice:

Import java.io.*;
Import java.nio.*;
Import java.nio.channels.*;
Import java.nio.charset.*;
Import java.net.*;
Import java.util.*;
    Class Nserver {private Selector Selector = null;
    static final int PORT = 30000;

    Private Charset Charset = Charset.forname ("UTF-8");
        public void Init () throws IOException {selector = Selector.open ();
        Serversocketchannel Server = Serversocketchannel.open ();
        Inetsocketaddress isa = new Inetsocketaddress ("127.0.0.1", PORT);
        Server.bind (ISA);
        Sets the ServerSocket to work server.configureblocking (false) in a non-blocking manner;

        Registers the server with the specified Selector object Server.register (selector,selectionkey.op_accept); while (Selector.select () >0) {//sequentially processes each selected Selectionkey for (Selectionkey sk:selector.se
                Lectedkeys ()) {Selector.selectedkeys (). Remove (SK);
                If the SK corresponding channel contains the client's connection request if (sk.isacceptable ()){Socketchannel sc = server.accept ();
                    Sc.configureblocking (FALSE);
                    Sc.register (Selector,selectionkey.op_read);
                Set the SK corresponding channel to be ready to accept other requests sk.interestops (selectionkey.op_accept); //If SK corresponding channel has data to read if (sk.isreadable ()) {//Get the S
                    Electionkey corresponding Channel Socketchannel sc = (socketchannel) sk.channel ();
                    Bytebuffer buff = bytebuffer.allocate (1024);
                    String content = "";
                            try {while (Sc.read (buff) >0) {
                            Buff.flip ();
                        Content + + charset.decode (buff);
                        } System.out.println ("Read data:" + content);
             Sk.interestops (Selectionkey.op_read);       //If there is an exception to the channel with SK, it indicates that the client of the channel is having a problem,//So cancel SK's note from selector
                        Volume catch (IOException e) {sk.cancel ();
                    if (Sk.channel ()!= null) Sk.channel (). Close ();
                        //Send the received data to all registered Selectionkey if (content.length () >0) { For (Selectionkey Key:selector.keys ()) {Channel
                            Targetchannel = Key.channel (); if (Targetchannel instanceof Socketchannel) {Socketchannel des
                                t = (socketchannel) Targetchannel;
                            Dest.write (content) (Charset.encode);

 }
                        }
                    }
                }
            }
        }
    }   public static void Main (string[] args) throws IOException {new Nserver (). Init ();
    } class Nclient {private Selector Selector = null;
    static final int PORT = 30000;
    Private Charset Charset = Charset.forname ("UTF-8");

    Private Socketchannel sc = null;
        public void Init () throws IOException {selector = Selector.open ();
        Inetsocketaddress isa = new Inetsocketaddress ("127.0.0.1", PORT);
        sc = Socketchannel.open (ISA);
        Sc.configureblocking (FALSE);
        Sc.register (Selector,selectionkey.op_read);
        Start the thread new Clientthread () that reads the server-side data. Start ();
        Create keyboard input stream Scanner scan = new Scanner (system.in);
            while (Scan.hasnextline ()) {String line = Scan.nextline ();
        Sc.write (line) (Charset.encode);
            }//define threads that read service-side data private class Clientthread extends thread {public void run () { try {WHile (Selector.select () >0) {//traverse channel corresponding Selectionkey for each available IO operation For (Selectionkey Sk:selector.selectedKeys ()) {Selector.selectedkeys (). Re
                        Move (SK);
                            if (sk.isreadable ()) {//Use NIO to read data in channel
                            Socketchannel sc = (socketchannel) sk.channel ();
                            Bytebuffer buff = bytebuffer.allocate (1024);
                            String content = "";
                                while (Sc.read (buff) >0) {sc.read (buff);
                                Buff.flip ();
                            Content + + charset.decode (buff);
                            } System.out.println ("Chat info:" + content);
                        Sk.interestops (Selectionkey.op_read);
}                    catch (IOException e) {E.PR
            Intstacktrace ();
    }} public static void Main (string[] args) throws IOException {new Nclient (). Init (); }
}

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.