java nio学习笔记

来源:互联网 发布:qt编程实现漂亮界面 编辑:程序博客网 时间:2024/06/04 20:33

NIO (new io / non blocking io)
first overview
channels and buffer
the data is read from a channel to buffer. and the data is written from buffer to a channel.
non blocking io
when the data is reading from channel or is writing to channel,the thread can do something else and the thread can continue process the data when the data is readed.
selectors
a selector object which can monitor multiple channels for events(like open a connection or close),thus,a single thread can monitor multiple channels for data.
java nio is consist of core componets with channels buffers and selectors.
the primary channel implementations in java is FileChannel(File) DatagramChannel(UDP) SocketChannel(TCP) and ServerSockedChannel(Listen TCP incoming connections,for each incoming connection a ServerSocketChannel is created).
the core buffer implementations in java is ByteBuffer ShortBuffer IntBuffer LongBuffer CharBuffer DoubleBuffer and FloatBuffer.
the MappedByteBuffer is used in conjunction with memory mapped file.
To use a selector,you can register the channel with it. then you can call it’s select(),this method will block until there is a event ready for one of the registered channels.

Channel
java nio channels are similar to stream with a few differences:
you can both read and write to a channel.
channel can be read and written asynchronously.
channel always read to or write from a Buffer.

Buffer
using a buffer to read and write data typically follows this little 4-steps process:
write data into buffer.
call flip() to switch buffer to read mode.
read data out of the buffer.
call clear() or compact().
a buffer has three properties you need to familiar,these are:
capacity
a buffer has a fixed size,you can only write capacity bytes,longs,chars etc. once the buffer is full,you must read or clear the buffer before you can write more data into it.
position
in the write mode,write data into buffer,you do so at a certain position,initially the position is 0,position can maximally become capacity-1.
in the read mode,read data from buffer,you do so at a certain position,when you call flip(),the position is reset back to 0.
limit
in write mode,the limit is the limit of how much data you can write into the buffer,the limit equal to the capacity of the buffer.
in read mode,the limit is the size of how much data you can read from the buffer,when you call flip(),the limit is set to write postion of write mode.
allocating a buffer
Buffer.allocate().
Writing data to a buffer
channel.read(buffer).
buffer.put().
flip()
switch a buffer to read mode from write mode,this method will set position to 0 and set limit to write postion of write mode.
reading data from a buffer
channel.write(buffer).
buffer.get().
rewind()
calling rewind() sets the postion to 0.
clear()
switches a buffer from reading mode to writing mode,this method will set position to 0 and set limit to capacity.
compact()
switches a buffer from reading mode to writing mode,but the method is different from clear(),the method will copy the unread data to the beginning of buffer,then,sets the position to the end of unread data and sets limit to capacity.
mark() and reset()
you can mark the position in a buffer by calling the mark(),then you can calling reset() to reset position to the marked position.
equals() and compareTo()

java nio scatter / gather
scatter
a scatter read allows you read a channel data into more than one buffer.
channel.read(buffer[]).
the scatter read fill up one buffer before moving on to the next.once a buffer is fill,the channel moves on to fill the next buffer.
gather
a gather write allows you write a channel data from more than one buffer.
channel.write(buffer[]).
only the data between position and limit is written,the channel moves to read data from the next buffer.

java nio channel to channel transfers
in java nio you can transfer data directly from one channel to another with transferTo() or transferFrom().
the SocketChannel implementation may only transfer data until the send or receive buffer is full.

java nio selector
a selector can examine one or more channels,and determine which channel is ready to reading or writing etc. this way a single thread can monitor multiple channels and multiple network connections.
creat a selector
Selector.open().
Register channel with a selector
SelectableChannel channel.configureBlocking(false);
SelectionKey key=channel.register(selector,SelectionKey.OP_CONNECT|OP_ACCEPT|OP_READ|OP_WRITE,attachObj);
the channel must be in non-blocking mode to be used with a selector.
a channel that has connected successfully to a another server is connect ready.
a server socket channel which accepts an connection is accept ready.
a channel that has data ready to read is read ready.
a channel that is ready for you to write data is write ready.
SelectionKey
a channel registered with a selector will return a SelectionKey object which has a few properties as follwing:interestSet readySet channel selector attachedObject.
interestSet is the set of events you are interseted in selection. SelectionKey.interestOps()
the ready set is the set of operations the channel is ready for.SelectionKey.readyOps()|key.isAcceptable()|key.isConnectable()|key.isReadable()|key.isWritable().
key.channel()|key.selector().
you can attach an object to a SelectionKey. key.attach(attachObj)|key.attachment().
Selecting channels via a selector
once you have register one or more channel with a selector you can call one of the select() methods. this method will return the channel count that ready for events you are interest in.
int select():the method blocks until at least one channel is ready for the events you registered fro.
int select(timeout):does the same as select except blocks for a maximum of timeout miliseconds.
int selectNow():doesn’t block at all.it returns immediately with whatever channel are ready.
the int returned by the select() which tells you how many channels are ready.that is,how many channel that become ready since last time you called select().
SelectedKeys()
once you called the select() method and its return the value indicated that one or more channels are ready.you can access the ready channels by calling the selector.selectedKeys() which returned the set of SelectionKey(Set). then you can iterate this set to access the ready channels.
notice the selector does not remove the SelectionKey from the set itself.so you have to do this when you are done processing the channel. the next time the channel becomes ready the selector will add it to the set again.
wakeUp()
a thread that calld the select() method which is blocked,can be made to leave the select() method,even if no channels are yet ready,this is done by a different thread call the wakeUp() method on the selector which the first thread has called select() on.the thread waiting inside select() will then return immediately.
if a different thread call the wakeUp() on a selector and no thread is currently blocked inseide select(),the next thread calls select() will wake up immediately
close()
this method close the selector and invalidates all the SelectionKeys register on the selector,but the channels themseleves are not closed.

FileChannel
a FileChannel is a channel that is connected to a file. using a file channel you can read data from a file and write data to a file.
a FileChannel cannot be set into non-blocking mode.
you cannot open a filechannel directly,you must obtain a filechannel via a inputstream,outputstream or a randomaccessfile.
Reading data from a filechannel
int readCount=channel.read(buffer).if -1 is returned,the end-of-file is reached.
Writing data to a FileChannel
channel.write(buffer).
Closing a FileChannel
channel.close().
FileChannel position,size,truncate,force.

SocketChannel
a java nio SocketChannel is a channel that is connected to a tcp network socket. there are two ways a SocketChannel can be created.
you open a SocketChannel and connect to a server somewhere on the internet.
A SocketChannel can be created when an incoming connections arrives at a ServerSocketChannel.
open and close a SocketChannel
channel=SocketChannel.open();
channel.connect(new InetSocketAddress(host,port));
channel.close();
reading or writing
int count=channel.read(buffer);
channel.write(buffer);
Non-blocking Mode
you can set a SocketChannel into non-blocking mode. then you can call connect(),read(),write() asynchronous mode, and you can call finishConnect() method to determine weather the connect is establised.
the non-blocking mode of SocketChannel works much better with selector.

ServerSocketChannel
a java nio ServerSocketChannel is a channel that can listen for incoming connections.
open or close a ServerSocketChannel
channel=ServerSocketChannel.open();
channel.bind(new InetSocketAddress(port));
channel.close();
listen for Incoming Connections
SocketChannel socketChannel=channel.accept();
this method will blocking until a incoming connection is arrived,and a SocketChannel can be created.
non-blocking mode
you can set a ServerSocketChannel into non-blocking mode by calling configureBlocking(false). in the mode the accept() method returns immediately, and may thus return null if no incoming connection had arrived.

non-blocking server

0 0
原创粉丝点击