Channel channels of Java NIO (ii)

Source: Internet
Author: User
Tags readfile


The Java NIO Channel has been described in an article, the channel is always written data, the first time to write data to Bytebuffer, read the data is always first read from the channel into the Bytebuffer. For example, this figure is commonly used in many well-known blogs, very good understanding of the channel.

650) this.width=650; "Src=" https://s4.51cto.com/wyfs02/M01/9E/4A/wKioL1mPKOfiRUviAAAlAoB14ME679.png-wh_500x0-wm_ 3-wmp_4-s_3716001730.png "title=" Qq20170813001014.png "alt=" Wkiol1mpkofiruviaaalaob14me679.png-wh_50 "/>


The channel is divided into several types:

    1. FileChannel

    2. Socketchannel

    3. Serversocketchannel

    4. Datagramchannel


FileChannel:

Often said FileChannel is to take the following example to say things

The code is as follows:

package com.nio.basic;import java.io.ioexception;import java.io.randomaccessfile;/** *  created by sdc on 2017/8/13. */public class randomaccessfiletest  {    public static void main (String[] args)  {         readfile ();    }    /**      *  read files      *  @throws  Exception      */    public static void readfile () {         String fileName =  "c:\\users\\sdc\\desktop\\gc  (2). Log";         RandomAccessFile randomAccessFile = null;         try{             randomAccessFile = New randomaccessfile (filename,  "R");             long filelength = randomaccessfile.length ();             system.out.print ("Length"  + filelength);             int start = 100;             randomaccessfile.seek (start);             byte[] bytes = new byte[20];             int read = 0;             while  ((Read = randomaccessfile.read (bytes))  !=  -1)  {                 system.out.println (New&nbsP String (bytes,  "UTF-8"));            }             system.out.println (bytes.length);             system.out.println (new String (bytes,   "UTF-8");        }catch  (exception e)  {             e.printstacktrace ();         }finally {             if  (randomaccessfile != null)  {                 try {                     randomaccessfile.close ();                 } catch  (ioexception e)  {                      E.printstacktrace ();                 }            }         }    }}


There are examples of this:

FileInputStream is = new FileInputStream (new File (SRC)); FileChannel Channelfrom = Is.getchannel ();

In fact, these two are used in the NIO channel, you might as well write an example to try.


Socketchannel and Serversocketchannel are generally two together, one for the client connection and one for the server connection.

package com.nio.basic;import java.io.ioexception;import java.net.inetsocketaddress;import  Java.nio.bytebuffer;import java.nio.channels.selectionkey;import java.nio.channels.selector;import  java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import  java.util.iterator;import java.util.set;/** * nio  Service End &NBSP;*&NBSP;CREATED&NBSP;BY&NBSP;SDC  on 2017/8/13. */public class nioserver {    bytebuffer  buffer = bytebuffer.allocate (1024x768);    public static void  Main (String[] args)  throws IOException {         System.out.println ("server started ...");        try {             new nioserver (). Run ();         } catch  (exception e)  {             e.printstacktrace ();        }    }     public void run  ()  throws  Exception {         //Open the server-side socket channel          Serversocketchannel serversocketchannel = serversocketchannel.open ();         //server-side set to non-blocking          Serversocketchannel.configureblocking (FALSE);         //Server binding          serversocketchannel.bind (new inetsocketaddress ("localhost",  8000)         //Register of events of interest          selector selector = selector.open ();  &nBsp;      serversocketchannel.register (selector, selectionkey.op_accept);         while  (True)  {             int selectcount = selector.select ();             if ( selectCount ==0 )  {                 continue;             }             selector.select ();             set<selectionkey> keys = selector.selectedkeys ();             //Get iterators              iterator<selectionKey> keyiterator = keys.iterator ();             while  (Keyiterator.hasnext ())  {                 selectionkey key = keyiterator.next ();                 if  (! Key.isvalid ())  {                     continue;                 }                 if  (Key.isacceptable ())  {                     serversocketchannel  ssctemp  =  (Serversocketchannel)  key. Channel ();                     //get a connected socketchannel and register it on selector, with an interest operation of read                     SocketChannel  Socketchannel = ssctemp.accept ();                     socketchannel.configureblocking (False);                      Socketchannel.register (Selector, selectionkey.op_read);                     system.out.println ("REGISTER  Channel , channel number is: " + selector.keys (). Size ());                 } else if  (Key.isreadable ())  {                     // Reading data from a channel                      SocketChannel channel =  (Socketchannel)  key.channel ();                     read ( channel);                 }                  Keyiterator.remove ();  //the event has been processed and can be discarded              }        }    }     Private void read (Socketchannel chaNnel)  throws IOException {        int count ;         buffer.clear ();         try {            while  (Count  = channel.read (buffer))  > 0)  {                 buffer.flip ();                 byte[] bytes = new byte[buffer.remaining () ];                buffer.get ( bytes);                 System.out.println ("Read from client:"  + new string (bytes));             }            if  (count  < 0)  {                 channel.close ();            }         } catch  (ioexception e)  {             e.printstacktrace ();         }    }}
package com.nio.basic;import java.io.ioexception;import java.net.inetsocketaddress;import  java.nio.bytebuffer;import java.nio.channels.socketchannel;import java.util.random;import  java.util.concurrent.executorservice;import java.util.concurrent.executors;import  java.util.concurrent.timeunit;/** * nio  Client  * Created by sdc on  2017/8/13. */public class nioclient {    public static void  main (String[] args)  {        ExecutorService  Executorservice = executors.newcachedthreadpool ();         Executorservice.submit (New client ("nio-client-1"));         Executorservice.submit (New client ("Nio-client-2"));         Executorservice.submit (New client ("nio-client-3"));         executorservice.shutdown ();    }     static class Client extends Thread {         private String clientThreadName;         Bytebuffer buffer = bytebuffer.allocate (1024x768);         Random random = new random (        client); String clientthreadname)  {             this.clientthreadname = clientthreadname;        }          @Override         public  void run ()  {             Socketchannel channel = null;            try {                 channel = socketchannel.open ();                 Channel.configureblocking (False);                 channel.connect (new inetsocketaddress ("localhost",  8000));                 while  (! Channel.finishconnect ())  {                     timeunit.microseconds.sleep (;     )            }                 for  (int i=0; i<5; i++)  {                     timeunit.microseconds.sleep (100 *  Random.nextint ());                     String message =  "send message "  + i +   " from"  + clientThreadName;                     buffer.put (Message.getbytes ());                      Buffer.flip ();                     //buffer first reads the data into buffer, and the channel first writes the data in buffer to the channel,          &nbsP;          channel.write (buffer);                     buffer.clear () ;                }             } catch  (ioexception e)  {                  E.printstacktrace ();            } catch  (interruptedexception e)  {                 e.printstacktrace ();             }finally {                 try {                     Channel.close ();                 } catch  (ioexception e)  {                     e.printstacktrace ();                 }             }        }     }}




This article is from the "no kuibu to thousands of Miles" blog, please be sure to keep this source http://shangdc.blog.51cto.com/10093778/1955874

Channel channels of Java NIO (ii)

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.