NIO Review 03

Source: Internet
Author: User

Socketchannel:

1. Socketchannel in Java NiO is a channel that is connected to a TCP network socket. Socketchannel can be created in the following 2 ways:

Open a socketchannel and connect to a server on the Internet.

When a new connection arrives at Serversocketchannel, a socketchannel is created.

2. open Socketchannel(Sender channel?) ):

    Socketchannel Socketchannel = socketchannel.open ();    Socketchannel.connect (new inetsocketaddress ("http://jenkov.com", 80));

3. Close Socketchannel: call Socketchannel.close () to close SocketChannel:socketChannel.close () when Socketchannel is exhausted;

4. Read data from Socketchannel: from Socketchannel (receiver channel? ) to read the data, call one of the Read () methods.

    Bytebuffer buf = bytebuffer.allocate ();     int bytesread = Socketchannel.read (BUF);

First, assign a buffer. The data read from Socketchannel will be placed in this buffer. Then, call Socketchannel.read (). This method reads the data from the Socketchannel into buffer. Read ()

The int value returned by the method indicates how many bytes were read into the buffer. If 1 is returned, it indicates that the end of the stream has been read (the connection is closed)

5. Write Socketchannel: Write data to Socketchannel (send Port channel?) ) is the Socketchannel.write () method, which takes a buffer as a parameter. Examples are as follows:

    String NewData = "New String to write to file ..." + system.currenttimemillis ();     = Bytebuffer.allocate ();    Buf.clear ();    Buf.put (Newdata.getbytes ());    Buf.flip ();      while (Buf.hasremaining ()) {             channel.write (BUF);    }

Note the call to the Socketchannel.write () method is in a while loop. The Write () method does not guarantee how many bytes can be written to Socketchannel. So, we repeatedly call write () until buffer has no bytes to write.

6. Non-blocking mode

The Socketchannel can be set to non-blocking modes (non-blocking mode). After setting up, you can downgrade the Connect (), read (), and write () in asynchronous mode.

Connect (): if Socketchannel is in nonblocking mode, call Connect () at this point, the method may return before the connection is established. In order to determine whether a connection is established, you can call the Finishconnect () method. Like this:

      Socketchannel.configureblocking (false);      Socketchannel.connect (new inetsocketaddress ("http://jenkov.com");        while (! Socketchannel.finishconnect ()) {              //Wait, or do something else ...       }

write (): in non-blocking mode, the write () method may return if nothing has been written. So you need to call write () in the loop. There are already examples, and we will not dwell on them here.

Read (): non-blocking mode, the read () method may return if no data has been read. So pay attention to its int return value, which tells you how many bytes were read.

nonblocking mode vs. selector: nonblocking mode works better with selectors, and by registering one or more socketchannel with selector, you can ask the selector which channel is ready to read, write, and so on.

Serversocketchannel

1. Serversocketchannel in Java NiO is a channel that can listen for incoming TCP connections, just like serversocket in standard IO. The Serversocketchannel class is in the Java.nio.channels package.

  Serversocketchannel Serversocketchannel =< Span style= "color: #000000;"    > Serversocketchannel.open (); Serversocketchannel.socket (). bind ( new  inetsocketaddress (9999));  while  (true  ) {Socketchannel Socketchannel  = Serversock              Etchannel.accept ();  //   

2. Open Serversocketchannel: over call Serversocketchannel.open () method to open Serversocketchannel. such as: Serversocketchannel Serversocketchannel = Serversocketchannel.open ();

3. Turn off Serversocketchannel: turn off Serversocketchannel by calling the Serversocketchannel.close () method. such as: Serversocketchannel.close ();

4. Listen for incoming connections: listen for incoming connections through the Serversocketchannel.accept () method. When the Accept () method returns, it returns a Socketchannel that contains the new incoming connection. Therefore, the accept () method

will always block until a new connection arrives. Typically, you will not just listen to one connection, but call the Accept () method in the while loop. As in the following example :

 while (true) {        = serversocketchannel.accept ();          // Do something with Socketchannel ... }

Of course, you can also use exit criteria other than true in the while loop.

5. Non-blocking mode

Serversocketchannel can be set to non-blocking mode. In nonblocking mode, the Accept () method returns immediately, or null if no new incoming connection has been entered. Therefore, you need to check if the returned Socketchannel is null.

Serversocketchannel Serversocketchannel =Serversocketchannel.open (); Serversocketchannel.socket (). Bind (NewInetsocketaddress (9999)); Serversocketchannel.configureblocking (false);  while(true) {Socketchannel Socketchannel=serversocketchannel.accept (); if(Socketchannel! =NULL){                 //Do something with Socketchannel ...           }     }

Java NIO Datagramchannel:

1. Datagramchannel in Java NiO is a channel that can send and receive UDP packets. Because UDP is a non-connected network protocol, it cannot be read and written like other channels. It sends and receives a packet.

2. Open Datagramchannel: The following is how Datagramchannel is opened:

Datagramchannel channel = Datagramchannel.open ();

Channel.socket (). bind (New Inetsocketaddress (9999));

This example opens the Datagramchannel that can receive packets on UDP port 9999.

3. Receive data: receive data from Datagramchannel via the Receive () method, such as:

Bytebuffer buf = Bytebuffer.allocate (48);

Buf.clear ();

Channel.receive (BUF);

The receive () method copies the received packet contents to the specified buffer. If buffer does not tolerate the data received, the extra data will be discarded.

4. Send data

Send data from Datagramchannel using the Send () method, such as:

     String NewData = "New String to write to file ..." + system.currenttimemillis ();      = Bytebuffer.allocate ();     Buf.clear ();     Buf.put (Newdata.getbytes ());     Buf.flip ();      int New Inetsocketaddress ("jenkov.com", 80));

This example sends a string of characters to UDP port 80 of the "jenkov.com" server. Because the server does not monitor this port, nothing happens. You will not be notified if the packets you sent have been received, because UDP has no guarantee of data transfer.

5. Connect to a specific address

Datagramchannel can be "connected" to a specific address in the network. Because UDP is not connected, connecting to a specific address does not create a true connection like a TCP channel. Instead, lock the Datagramchannel and make it available only from

Send and receive data at a specific address. Here's an example:

Channel.connect (new inetsocketaddress ("jenkov.com", 80));

when connected, you can also use the read () and write () methods, just as you would with a traditional channel. There is no guarantee of data transfer. Here are a few examples:

      int bytesread = channel.read (buf);       int Byteswritten = channel.write (But);

Pipe

1. The Java NIO pipeline is a one-way data connection between 2 threads. The pipe has a source channel and a sink channel. The data is written to the sink channel, which is read from the source channel.

2. Create a pipeline: Open the pipeline with the Pipe.open () method. For example:

Pipe pipe = Pipe.open ();

3. Write data to the pipeline: to write data to the pipeline, you need access to the sink channel. Like this:

By calling Sinkchannel's write () method, the data is written to Sinkchannel, like this:

String NewData = "New String to write to file ..." + system.currenttimemillis ();     = Bytebuffer.allocate ();    Buf.clear ();    Sbuf.put (Newdata.getbytes ());    Buf.flip ();      while (Buf.hasremaining ()) {           sinkchannel.write (BUF);    }

4. read data from the pipeline: the data from the read pipeline requires access to the source channel, like this:

Pipe.sourcechannel Sourcechannel = Pipe.source ();

Call the source channel's read () method to read the data, like this:

    Bytebuffer buf = bytebuffer.allocate ();     int bytesread = Sourcechannel.read (BUF);

the int value returned by the Read () method tells us how many bytes were read into the buffer.

NIO Review 03

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.