JAVA NiO Series (ii) channel interpretation

Source: Internet
Author: User

Channels are a channel for transmitting data, both buffers and entities (files or sockets), and the characteristics of the channel (which is also characteristic of NIO): The data in the channel is always read into a buffer, or it is always read from a buffer.

Classification of Channel

1) FileChannel: Read and write data from the file

2) Socketchannel: Read and write data in the network via TCP protocol

3) Serversocketchannel: A new incoming TCP connection can be monitored on the server side, like a Web server, to create a socketchannel for each new incoming request

4) Datagramchannel: Read and write data in the network via UDP protocol

Many of the above classifications correspond to different entities, including file Io, TCP, and UDP network IO.

Let's look at the source of the channel:

1  Public Interface extends closeable {  2  8      Public Boolean IsOpen (); 9  -      Public void throws IOException;  -  }

From here we can see that the channel interface only provides the two methods of shutting down the channel and detecting whether the channel is open, and the remaining methods are defined by the child interface and the implementation class.

We choose several of them to see the source code of these interfaces:

 1  public  interface   Writablebytechannel  2  extends   Channel  3  4  5  public  int  Write (bytebuffer src) throws   IOException;  6  7 } 
 Public Interface extends
{
Public int throws IOException;}
 Public Interface Bytechannel     extends Readablebytechannel, writablebytechannel{}

I mentioned earlier: the channel can read-only, write-only or read-write at the same time, because the channel class can only implement read-only interface Readablebytechannel or only implement write-only interface Writablebytechannel, And we commonly used channel class FileChannel, Socketchannel, Datagramchannel is two-way communication, because the implementation of the Bytechannel interface.

Access to Channel

IO can be broadly divided into: file io and network IO. The channel for file IO corresponds to FileChannel, while network IO corresponds to three channels: Socketchannel, Serversoketchannel, and Datagramchannel.

One, the file channel

FileChannel objects cannot be created directly, but can only be obtained by Getchannel () of FileInputStream, OutputStream, Randomaccessfile objects, such as:

New FileInputStream ("C:/in.txt"= Fis.getchannel ();

FileChannel cannot be set to non-blocking mode, it is always running in blocking mode.

1) Use the channel to read the file
1  Public classniofilereadtest2 {3      Public Static voidMain (string[] args)throwsIOException4     {5Randomaccessfile RAF =NewRandomaccessfile ("D:/in.txt", "RW");6FileChannel FIS =Raf.getchannel ();7Bytebuffer buffer = bytebuffer.allocate (1024);8 fis.read (buffer);9 Buffer.flip ();Ten          while(Buffer.hasremaining ()) One         { ASystem.out.print ((Char) Buffer.get ()); -         } - buffer.clear (); the fis.close (); -     } -}

Execution Result:

Filechannelbytebufferselectorpicked
2) writing files using channels
 Public classniofilewritetest{ Public Static voidMain (string[] args)throwsException {fileoutputstream fos=NewFileOutputStream ("D:/out.txt"); FileChannel FC=Fos.getchannel (); Bytebuffer Buffer= Bytebuffer.allocate (10);        Buffer.clear (); String Str= "Channel";        Buffer.put (Str.getbytes ());        Buffer.flip ();  while(Buffer.hasremaining ()) {fc.write (buffer);        } fc.close ();    Fos.close (); }}

Always remember that the channel is to be closed.

Bytebuffer method in the next chapter in detail, as long as note this: The channel can only use Bytebuffer, whether it is read or write, the channel will be docking buffer .

3) Common methods of channel

Position (); Returns the file location of the channel

Position (long Newposition): Sets the file location of the channel

Modify the above-mentioned program to observe the following methods:

1  Public classniofilereadtest2 {3      Public Static voidMain (string[] args)throwsIOException4     {5Randomaccessfile RAF =NewRandomaccessfile ("D:/in.txt", "RW");6FileChannel FIS =Raf.getchannel ();7SYSTEM.OUT.PRINTLN ("Total length of this channel file:" +fis.size ());8         //the file location of the current channel9         LongPosition =fis.position ();TenSYSTEM.OUT.PRINTLN ("Channel Current position:" +position); One         //set a new channel file location to start reading from this location AFis.position (position + 8); -Bytebuffer buffer = bytebuffer.allocate (50); - fis.read (buffer); the Buffer.flip (); -          while(Buffer.hasremaining ()) -         { -System.out.print ((Char) Buffer.get ()); +         } - buffer.clear (); + fis.close (); A     } at}

Execution Result:

Total length of this channel file: Channel current position:0Nelbytebufferselector

FileChannel is thread-safe, and multiple threads can operate concurrently on the same instance, but some of these methods (methods for changing the file channel location or file size) must be single-threaded.

Second, the network channel

Socketchannel is a channel that is connected to a TCP socket and is obtained in one of two ways:

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

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

The above two modes are similar to the IO socket, ServerSocket, the following to see the client and server side:

First, Socketchannel

Reading data from the channel

1  Public classsocketchanneltest2 {3      Public Static voidMain (string[] args)throwsException4     {5         //Get socket Channel6Socketchannel sc =Socketchannel.open ();7         //set to non-blocking mode8Sc.configureblocking (false);9         //establish a connection, in non-blocking mode, the method may return before the connection is establishedTenSc.connect (NewInetsocketaddress ("wap.cmread.com", 80)); One         //determine if the connection is established A          while(!sc.finishconnect ()) -         { -SYSTEM.OUT.PRINTLN ("Connection not established"); theThread.Sleep (5); -         } -Bytebuffer buffer = Bytebuffer.allocate (48); -         intByteread =sc.read (buffer); + System.out.println (byteread); - sc.close (); + buffer.clear ();  A     } at}

implementation results;

Connection not established connection not established 0

1, 6th, 7 line is to get a socket channel, and set to non-blocking mode.

2, because of the non-blocking mode, the channel in the call method Connect/read/writer these three methods, this occurs: the connection is not established, the Connect method returns, no data has been read, the Read method returns; Writer will return .

3, in the 12 line of the loop code, is to determine whether the connection is established, from the execution results, the loop executes two connections before the establishment (in the loop thread and sleep).

4, because just established the connection, the channel inside actually does not have any data.

5. Line 18th calls the Read method and, because it is non-blocking mode, returns 0 without reading any data (although there is no data in the channel).

Writing data to a channel

1  Public classsocketchanneltest2 {3      Public Static voidMain (string[] args)throwsException4     {5Socketchannel sc =Socketchannel.open ();6String str = "non-blocking Socket Channel";7Bytebuffer buffer = bytebuffer.allocate (100);8 Buffer.put (Str.getbytes ());9 Buffer.flip ();Ten          while(Buffer.hasremaining ()) One         { A sc.write (buffer); -         } - sc.close (); the buffer.clear (); -     } -}

1. The invocation of 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.

Second, Serversocketchannel

The Serversocketchannel is a channel that can listen for incoming TCP connections.

1  Public classserversocketchanneltest2 {3      Public Static voidMain (string[] args)throwsException4     {5Serversocketchannel SSC =Serversocketchannel.open ();6Ssc.socket (). Bind (NewInetsocketaddress (80));7Ssc.configureblocking (false);8          while(true)9         {TenSocketchannel sc =ssc.accept (); One             if(NULL!=SC) A             { -                 //Do something; -             } the         } -     } -}

1, 5th, 6, 7 line, get a serversocketchannel, and listen to 80 port, set to non-blocking mode.

2, through the Accept method to listen to the new incoming connection, this method will return a new incoming connection Socketchannel (server-side access to the channel). In the case of blocking mode, the method will block until a new connection comes in. If non-blocking mode, the Accept method returns immediately and the return value is null.

3, line 11th, because in non-blocking mode, you need to check if Socketchannel is null.

Third, socket channel and socket
1 serversocketchannel SSC = serversocketchannel.open (); 2 serversocket socket = ssc.socket (); 3 Serversocketchannel ssc1 = Socket.getchannel ();

1, from this code snippet you can probably see a relationship: all socket channels (Socketchannel/serversocketchanne/datagramsocketchannel) after being instantiated, Are all accompanied by the corresponding Socket object, which is the Java.net class (Socket/serversocket/datagramsocket) described in the previous IO section. Obtained through the socket method of the Channel class.

2. The Java.net Class (Socket/serversocket/datagramsocket) can now obtain the corresponding channel through the Getchannel method. The premise is that these socket objects are not created using traditional methods (direct instantiation). Otherwise it does not have an associated socket channel, and calling the Getchannel method returns always null.

JAVA NiO Series (ii) channel interpretation

Related Article

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.