Introduction to Java NIO components
Channel
A Channel is a bit like a stream. Data can be read from a Channel to Buffer and written from Buffer to a Channel. Here’s a picture:
Here are some implementations of the major channels in JAVA NIO:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
So we’re going to focus on SocketChannel and ServerSocketChannel
1 ServerSocketChannel
ServerSocketChannel is a channel that listens for incoming TCP connections, just like the ServerSocket in standard IO. Example code:
/ / open the ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// Listen on port 9999
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
// Set to non-blocking mode
serverSocketChannel.configureBlocking(false);
while(true) {// Setting to non-blocking mode causes the Accept method to return immediately, so null may be returned
SocketChannel socketChannel =
serverSocketChannel.accept();
//do something with socketChannel...
}
Copy the code
2 SocketChannel
A SocketChannel is a channel that connects to a TCP network socket. As in 1.1, a SocketChannel can be created when a connection arrives.
(1) Read SocketChannel data into the buffer:
ByteBuffer buf = ByteBuffer.allocate(2048);
int bytesRead = socketChannel.read(buf);
Copy the code
The int returned by the read() method indicates how many bytes were read into the Buffer. If -1 is returned, the end of the stream has been read (the connection is closed).
(2) Write buffer data to SocketChannel
String newData = "hello world";
// The Buffer operation is described in the following sections
ByteBuffer buf = ByteBuffer.allocate(2048);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
channel.write(buf);
}
Copy the code
Note that the write() method is placed inside the body of the while loop, because there is no guarantee of how many bytes will be written into a SocketChannel at a time.
(3) Non-blocking mode
socketChannel.configureBlocking(false);
Copy the code
Write () : In non-blocking mode, the write() method may return without writing anything. Read () : In non-blocking mode, the read() method may return before any data has been read. Non-blocking mode works well with a Selector, and by registering one or more socketchannels with a Selector, you can ask a Selector which channel is ready to read, write, etc., so let’s look at the Selector.