_ Example of use under NIO and NIO _ example of use
1. dispersion and aggregation
1. Scattering Reads:Channel in progressData is distributed to multipleBuffer ZoneMedium
2. Aggregate write (Gathering Writes): MultipleBuffer ZoneData inChannelMedium
Public void test4 () throws IOException {
RandomAccessFile raf1 = new RandomAccessFile ("1.txt"," rw ");
// 1. Obtain the channel
FileChannel channel1 = raf1.getChannel ();
// 2. Allocate a buffer of the specified size
ByteBuffer buf1 = ByteBuffer. allocate (100 );
ByteBuffer buf2 = ByteBuffer. allocate (1024 );
// 3. Distributed reading
ByteBuffer [] bufs = {buf1, buf2 };
Channel1.read (bufs );
// 4. Clustered write
RandomAccessFile raf2 = new RandomAccessFile ("2.txt"," rw ");
FileChannel channel2 = raf2.getChannel ();
Channel2.write (bufs );
}
Ii. Charset
Public void test6 () throws IOException {Charset cs1 = Charset. forName ("GBK"); // obtain the CharsetEncoder ce = cs1.newEncoder (); // obtain the decoder CharsetDecoder cd = cs1.newDecoder (); CharBuffer cBuf = CharBuffer. allocate (1024); cBuf. put ("character set! "); CBuf. flip (); // encoding ByteBuffer bBuf = ce. encode (cBuf); for (int I = 0; I <12; I ++) {System. out. println (bBuf. get ();} // decodes bBuf. flip (); CharBuffer cBuf2 = cd. decode (bBuf); System. out. println (cBuf2.toString (); System. out. println ("----------------------------------------------------"); Charset cs2 = Charset. forName ("UTF-8"); bBuf. flip (); CharBuffer cBuf3 = cs2.decode (bBuf); System. out. println (cBuf3.toString ());}
Iii. Non-blocking type of NIO (core: Selector)
Selector is a component that can detect one or more NIO channels in Java NIO and know whether the channel is prepared for read/write events. In this way, a single thread can manage multiple channels to manage multiple network connections.
1. TCP
Eg: client and server
// Client @ Testpublic void client () throws IOException {// 1. obtain the channel SocketChannel sChannel = SocketChannel. open (new InetSocketAddress ("127.0.0.1", 9898); // 2. switch non-blocking mode sChannel. configureBlocking (false); // 3. allocate the buffer ByteBuffer buf = ByteBuffer of the specified size. allocate (1024); // 4. send data to the server's external scan = new external (System. in); while (scan. hasNext () {String str = scan. next (); buf. put (new Date (). toString () + "\ n" + str ). getBytes (); buf. flip (); sChannel. write (buf); buf. clear ();} // 5. close the channel sChannel. close () ;}// server @ Testpublic void server () throws IOException {// 1. obtain the channel ServerSocketChannel ssChannel = ServerSocketChannel. open (); // 2. switch to the non-blocking mode ssChannel. configureBlocking (false); // 3. bind to connect to ssChannel. bind (new InetSocketAddress (9898); // 4. obtain Selector selector = Selector. open (); // 5. register the channel to the selector and specify the "Listening to receive events" ssChannel. register (selector, SelectionKey. OP_ACCEPT); // 6. round-Robin get the "ready" event on the selector while (selector. select ()> 0) {// 7. obtain all the registered "selection keys (listener events ready)" Iterator <SelectionKey> it = selector in the current selector. selectedKeys (). iterator (); while (it. hasNext () {// 8. the event SelectionKey sk = it. next (); // 9. determine what events are ready if (sk. isAcceptable () {// 10. if "receiving is ready", obtain the client connection SocketChannel sChannel = ssChannel. accept (); // 11. switch non-blocking mode sChannel. configureBlocking (false); // 12. register the channel to the selector. register (selector, SelectionKey. OP_READ);} else if (sk. isReadable () {// 13. gets the channel SocketChannel sChannel = (SocketChannel) sk in the "Read-ready" status on the current selector. channel (); // 14. read data ByteBuffer buf = ByteBuffer. allocate (1024); int len = 0; while (len = sChannel. read (buf)> 0) {buf. flip (); System. out. println (new String (buf. array (), 0, len); buf. clear () ;}// 15. deselect the SelectionKeyit key. remove ();}}}
2. UDP DatagramChannel
public void send() throws IOException{DatagramChannel dc = DatagramChannel.open();dc.configureBlocking(false);ByteBuffer buf = ByteBuffer.allocate(1024);Scanner scan = new Scanner(System.in);while(scan.hasNext()){String str = scan.next();buf.put((new Date().toString() + ":\n" + str).getBytes());buf.flip();dc.send(buf, new InetSocketAddress("127.0.0.1", 9898));buf.clear();}dc.close();}@Testpublic void receive() throws IOException{DatagramChannel dc = DatagramChannel.open();dc.configureBlocking(false);dc.bind(new InetSocketAddress(9898));Selector selector = Selector.open();dc.register(selector, SelectionKey.OP_READ);while(selector.select() > 0){Iterator<SelectionKey> it = selector.selectedKeys().iterator();while(it.hasNext()){SelectionKey sk = it.next();if(sk.isReadable()){ByteBuffer buf = ByteBuffer.allocate(1024);dc.receive(buf);buf.flip();System.out.println(new String(buf.array(), 0, buf.limit()));buf.clear();}}it.remove();}}
Iv. PIpe Pipeline
The Java NIO pipeline is a one-way data connection between two threads. Pipe has a source pipe and a sink pipe. Data will be written to the sink channel and read from the source channel.
Public void test1 () throws IOException {// 1. obtain the pipeline Pipe pipe = Pipe. open (); // 2. write Data in the buffer to the pipe ByteBuffer buf = ByteBuffer. allocate (1024); Pipe. sinkChannel sinkChannel = pipe. sink (); buf. put ("send data through one-way pipeline ". getBytes (); buf. flip (); sinkChannel. write (buf); // 3. read the data Pipe in the buffer. sourceChannel sourceChannel = pipe. source (); buf. flip (); int len = sourceChannel. read (buf); System. out. println (new String (buf. array (), 0, len); sourceChannel. close (); sinkChannel. close ();}