The channel of Java NIO

Source: Internet
Author: User

Channel: defined by the Java.nio.channels package. The Channel represents the connection that the IO source opens to the target. Channel is similar to the traditional "flow". Only the channel itself cannot directly access the data, and the channel can only interact with buffer.

  Ii. Important realization of channel

    • FileChannel: Read and write operation files
    • Socketchannel: Read and write network data over TCP
    • Serversocketchannel: Listen to the TCP connection, you can use it to create a simplest Web server
    • Datagramchannel: Read and write network data via UDP

Iii. FileChannel file reading and writing

1) Read and write data using the Transferto provided by the FileChannel itself.

Package Com.troy.nio.application;import Java.io.fileinputstream;import java.io.fileoutputstream;import Java.nio.channels.FileChannel; Public classChannel { Public Static voidMain (string[] args) throws Exception {//Read FileFileInputStream FileInputStream =NewFileInputStream ("D:/t.txt"); //Write a fileFileOutputStream FileOutputStream =NewFileOutputStream ("D:/e.txt"); //get read ChannelFileChannel Inchannel =Fileinputstream.getchannel (); //Get write ChannelFileChannel Outchannel =Fileoutputstream.getchannel (); //finish writing the dataInchannel.transferto (0, Inchannel.size (), Outchannel); }}

2) Use the Read/write method provided by FileChannel

Package Com.troy.nio.application;import Java.io.fileinputstream;import java.io.fileoutputstream;import Java.nio.bytebuffer;import Java.nio.channels.FileChannel; Public classChannel { Public Static voidMain (string[] args) throws Exception {//Read FileFileInputStream FileInputStream =NewFileInputStream ("D:/t.txt"); //Write a fileFileOutputStream FileOutputStream =NewFileOutputStream ("D:/e.txt"); //get read ChannelFileChannel Inchannel =Fileinputstream.getchannel (); //Get write ChannelFileChannel Outchannel =Fileoutputstream.getchannel (); //CacheBytebuffer Bytebuffer = Bytebuffer.allocate (1024x768); //reading Data         while(Inchannel.read (bytebuffer)! =-1) {            //convert to read/writeBytebuffer.flip (); System. out. println (NewString (Bytebuffer.array (),"GBK"). Trim ()); //write data, clear cacheOutchannel.write (Bytebuffer);        Bytebuffer.clear (); }    }}

Four, Socketchannel and Serversocketchannel at the same time, both are TCP protocol transmission, in the use of the above comparison service specific protocol control

The specific application can be consulted: http://www.cnblogs.com/ll409546297/p/7929646.html

V. Ways of Datagramchannel

1) Client

import Java.net.inetsocketaddress;import java.nio.bytebuffer;import java.nio.channels.DatagramChannel; Public classUdpClient { Public Static voidMain (string[] args) throws Exception {//get UDP channelDatagramchannel Datagramchannel =Datagramchannel.open (); //set non-blockingDatagramchannel.configureblocking (false); //Send DataDatagramchannel.send (Bytebuffer.wrap ("Hello server!". GetBytes ()),NewInetsocketaddress ("localhost",9000)); }}

2) 2 in the service side, blocking and non-blocking

1, blocking

Import Java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.bytebuffer;import Java.nio.channels.DatagramChannel; Public classUdpserver {//UDP channel    Private StaticDatagramchannel Datagramchannel;  Public Static voidMain (string[] args) throws Exception {Serverinit ();    Listen (); }    //Initialize    Private Static voidServerinit () throws IOException {//get UDP channelDatagramchannel =Datagramchannel.open (); //set up a receive portDatagramchannel.socket (). Bind (NewInetsocketaddress (9000)); }    //Monitor    Private Static voidListen () throws IOException { while(true) {            //Length of receptionBytebuffer Bytebuffer = Bytebuffer.allocate (1024x768); //this will block .datagramchannel.receive (Bytebuffer);            Bytebuffer.flip (); System. out. println (NewString (Bytebuffer.array ()). Trim ()); }    }}

2, non-blocking, using selector to make data selection

Import Java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.bytebuffer;import Java.nio.channels.datagramchannel;import Java.nio.channels.selectionkey;import Java.nio.channels.Selector;import Java.util.Iterator; Public classUdpserver {//Selector Selector    Private StaticSelector Selector; //UDP channel    Private StaticDatagramchannel Datagramchannel;  Public Static voidMain (string[] args) throws Exception {Serverinit ();    Listen (); }    //Initialize    Private Static voidServerinit () throws IOException {//Get selectorselector =Selector.open (); //get UDP channelDatagramchannel =Datagramchannel.open (); //set non-blockingDatagramchannel.configureblocking (false); //set up a receive portDatagramchannel.socket (). Bind (NewInetsocketaddress (9000)); //RegisterDatagramchannel.register (selector, selectionkey.op_read); }    //Monitor    Private Static voidListen () throws IOException { while(true) {Selector.Select(); Iterator<SelectionKey> iterator =Selector.selectedkeys (). iterator ();  while(Iterator.hasnext ()) {Selectionkey Selectionkey=Iterator.next (); if(Selectionkey.isreadable ()) {//Length of receptionBytebuffer Bytebuffer = Bytebuffer.allocate (1024x768); //There's no blocking .datagramchannel.receive (Bytebuffer);                    Bytebuffer.flip (); System. out. println (NewString (Bytebuffer.array ()). Trim ()); }            }        }    }}

Six, basically the channel implementation of the use of these, but it will involve a lot of details of the use, this need to further study

The channel of Java NIO

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.