The Serversocketchannel and Socketchannel of Java NIO

Source: Internet
Author: User

    • Serversocketchannel
    • Serversocketchannel role? What's the full-time thing?

1, listen to the new incoming TCP link channel,

2. Create a new Socketchannel

    • Serversocketchannel does not have any ability

Serversocketchannel does not have the ability to transmit data

    • How to create an Serversocketchannel instance

serversocketchannel Socketchannel =serversocketchannel.open ();

the object is associated with an unbound ServerSocket channel .

    • Serversocketchannel Binding Listening Port number

before JDK1.7, you need to call Serversocketchannel's socket method and call bind () to associate

after JDK1.7, you can call Serversocketchannel's bind () directly for port binding.

    • Serversocketchannel How to listen for new incoming connections

The new incoming connection is monitored by the serversocketchannel.accept () method.

serversocketchannel Default is blocking mode, you can view the JDK source code

as shown in the following:

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M00/A6/24/wKioL1nJ-D3Dah5AAACBgx4mDVg029.png "style=" float : none; "title=" 001.png "alt=" Wkiol1nj-d3dah5aaacbgx4mdvg029.png "/>

650) this.width=650; "src=" Https://s5.51cto.com/wyfs02/M02/A6/24/wKioL1nJ-D7zV0-tAAEvzfU0Jfg944.png "style=" float : none; "title=" 002.png "alt=" Wkiol1nj-d7zv0-taaevzfu0jfg944.png "/>

650) this.width=650; "src=" Https://s5.51cto.com/wyfs02/M01/07/73/wKiom1nJ-HvyXubDAACmTqkVkd8204.png "style=" float : none; "title=" 003.png "alt=" Wkiom1nj-hvyxubdaacmtqkvkd8204.png "/>


through Serversocketchannel.configureblocking (True) to set the blocking mode

1, in the blocking mode,

If there is a new connection coming in, then the Accept () method returns a Socketchannel that contains the new incoming connection.

If there is no new connection, then the Accept () method will always block here until some new connections come in .

2, Serversocketchannel in non-blocking mode . Configureblocking (False)

If there is a connection coming in, then the Accept () method returns a Socketchannel that contains the newly entered connection

If there is no new connection, then the accept () method returns null immediately


3. What are the fundamental differences between blocking mode and non-blocking mode?

in fact, it is in the absence of new connections, how to deal with the situation? Do not return, have been waiting for the words, is blocking;

if it returns immediately, it is non-blocking.


    • Socketchannel
    • How to create Socketchannel?

mode one: Create on client

Socketchannel Socketchannel = Socketchannel.open ();

mode two: Create on server side

Serversocketchannel received after accepting a connection request, as

Socketchannel Socketchannel = serversocketchannel.accept ();

    • Read the data in the pipeline into the cache, using the Socketchannel Read method

int read = Socketchannel.read (Sizebuffer);

    • Writes the data in the cache to the pipeline, using the Socketchannel write method

Socketchannel.write (Sizebuffer);

Examples are as follows:

Service side:

Package xingej.channel;import java.io.ioexception;import java.net.inetsocketaddress;import  java.nio.ByteBuffer;import java.nio.channels.ServerSocketChannel;import  java.nio.channels.socketchannel;public class serversocketchanneltest {     Public void initchannel ()  throws IOException {         //server side, through the open method, to create serversocketchannel        //note that at this time, the server side , there is no binding port yet         serversocketchannel serversocketchannel =  serversocketchannel.open ();         //is set to non-blocking mode//         serversocketchannel.configureblocking (False);         //binding port number after         //jdk1.7 version          serversocketchannel. Bind (New inetsocketaddress (8081));         //jdk1.7 before version         serversocketchannel.socket (). Bind (New inetsocketaddress ( 8081));         //Create byte buffers         The size of the  //buffer is 1024 bytes, which can be debugged yourself, such as changing to 64,128....        bytebuffer  Bytebuffer = bytebuffer.allocate (1024x768);        while  ( true)  {            system.out.println ("------ -Server-side-----Start receiving connections from-----clients---------");             / /On the server side, receive the link of the client, if there is a client, return a             // Socketchannel Object             //If it's blocking mode, there's no new link coming in, Will clog up here, otherwise, go down and execute   &NBsp;         //if the non-blocking mode, no new links come in, will immediately return a null, the program will not block here,  The            //will go down immediately              SocketChannel socketChannel =  Serversocketchannel.accept ();            if  ( Null != socketchannel)  {                 while  (True)  {                     //clear buffer data, can receive new data                       Bytebuffer.clear ();                     //reading the data from the pipeline Socketchannel to the   cacheBytebuffer                      //readSize  represents the number of bytes   reads                      int readSize =  Socketchannel.read (Bytebuffer);                     if  (readsize == -1)  {                          break;                     }                     //additional   business logic operations from the   byte cache,                     //  Note that the byte types used in the buffers here                      //  Therefore, if other types are needed, Need to convert                      system.out.println (New string (Bytebuffer.array ()));                 }             }            try {                 thread.sleep ( );            } catch  ( Interruptedexception e)  {                 e.printstacktracE ();            }         }    }    public static void main ( String[] args)  throws ioexception {        new  serversocketchanneltest (). Initchannel ();     }}


The client is as follows:

Package xingej.channel;import java.io.ioexception;import java.net.inetsocketaddress;import  java.nio.bytebuffer;import java.nio.channels.socketchannel;public class socketchanneltest  {    public void connectserver ()  throws IOException{         //  Create a  socketchannel object,         //  Please note that there is no   link to the server side Oh         SocketChannel  Socketchannel = socketchannel.open ();         //Start link server side         socketchannel.connect (new inetsocketaddress ("localhost",  8081));         //create   byte buffers in client          bytebuffer bytebuffer = bytebuffer.allocate (1024x768);         string msg =  "\nhello, nio, hello ,spark, hello ,hadoop, flume,  Mesos, marathon, netty, mina, stream, inputstream, outputstream \n " +                  "hello,  nio, hello ,spark, hello ,hadoop, flume, mesos, marathon, netty,  Mina, stream, inputstream, outputstream \n " +                  "hello, nio, hello ,spark,  hello ,hadoop, flume, mesos, marathon, netty, mina, stream,  inputstream, outputstream  Beijing \ n ";         //to byte buffers, add data          bytebuffer.put (Msg.getbytes ());         //  to update the limit value,This value is updated to position for the next read Operation         bytebuffer.flip ();         while (Bytebuffer.hasremaining ())  {             //writes the data in the byte cache to the pipeline              socketchannel.write (Bytebuffer);        }         socketchannel.close ();    }     public static void main (String[] args)  throws IOException{         new socketchanneltest (). ConnectServer ();     }}


Starting mode:

Start the server-side first, and then start the client










This article is from the "Xej Distributed Studio" blog, so be sure to keep this source http://xingej.blog.51cto.com/7912529/1968844

The Serversocketchannel and Socketchannel of Java NIO

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.