(1)channel
filechannel(cannot used with sector as it's blocking) socketchannel serversocketchannel
datagramchannel(for udp)
serversocketchannel is responsible for monitoring tcp connection
main functions:
serersocketchannel open()
socketchannel accept() accept connection from client
sercersocket socket()
a sample:
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);
while(true){
SocketChannel socketChannel =
serverSocketChannel.accept();
if(socketChannel != null){
//do something with socketChannel...
}
}
socketchannel
(2)buffer
types:
ByteBuffer
MappedByteBuffer
CharBuffer
DoubleBuffer
FloatBuffer
IntBuffer
LongBuffer
ShortBuffer
perporties:
capacity
position
limit
functions:
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf); //read into buffer.
buf.put(127);
int bytesWritten = inChannel.write(buf);//read from buffer into channel.
byte aByte = buf.get();
flip()// change from read mode to write mode. set position to 0 and limit to previous position
a sample:
01 RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
02 FileChannel inChannel = aFile.getChannel();
03
04 //create buffer with capacity of 48 bytes
05 ByteBuffer buf = ByteBuffer.allocate(48);
06
07 int bytesRead = inChannel.read(buf); //read into buffer.
08 while (bytesRead != -1) {
09
10 buf.flip(); //make buffer ready for read
11
12 while(buf.hasRemaining()){
13 System.out.print((char) buf.get()); // read 1 byte at a time
14 }
15
16 buf.clear(); //make buffer ready for writing
17 bytesRead = inChannel.read(buf);
18 }
19 aFile.close();
(3)sector
functions:
int select() // blocking until an event comes;
int select(long timeout)
int selectNow()
Set selectedKeys = selector.selectedKeys();
a sample:
Selector selector = Selector.open(); // get a slector
channel.configureBlocking(false); // set nonblocking
SelectionKey key = channel.register(selector, SelectionKey.OP_READ); // channel register to a slector with interesting events;
while(true) {
int readyChannels = selector.select(); // blocking until an event comes;
if(readyChannels == 0) continue; // if no event changed, it will return 0;
Set selectedKeys = selector.selectedKeys();
Iterator keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (key.isConnectable()) {
// a connection was established with a remote server.
} else if (key.isReadable()) {
// a channel is ready for reading
} else if (key.isWritable()) {
// a channel is ready for writing
}
keyIterator.remove();
}
}