The latest slide deck about Java NIO.2 from *instinctools Java developer Alexandr Brui. You can find here Java NIO.2 design, work with data, selector & channels, reading & writing and many more.
2. Network socket
Network socket is an endpoint of a connection across a computer network.
Main types of Internet socket:
● Datagram sockets, which use User Datagram Protocol (UDP).
● Stream sockets, which use Transmission Control Protocol (TCP) or Stream
Control Transmission Protocol (SCTP).
● Raw sockets, typically available in routers and other network equipment.
4. Java.IO - Stream-oriented
Data Source Program
Data
Destination Program
001001001111001001001001011
001001001111001001001001011
5. Java.IO - Blocking I/O
Socket Thread
read data, block until ready
read data, block until ready
write data, block until ready
write data, block until ready
6. Java.IO — Work with data
// read from socket
Scanner sc = new Scanner(socket.getInputStream());
String string = sc.nextLine();
System.out.println("Received " + string);
// write to socket
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println("Hello");
7. Java.NIO — Buffer-oriented & Non-blocking I/O
Channel Buffer Thread
read data into buffer
fill data into buffer
check data in buffer
goto top
8. Java.NIO — Work with data
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
// prepare to read
readBuffer.clear();
SocketChannel channel = getChannel();
channel.read(readBuffer);
readBuffer.flip();
// reading the buffer
// ...............…
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
// prepare to put data
writeBuffer.clear();
// putting the data
// ...............
// prepare to write
writeBuffer.flip();
channel.write(writeBuffer);
9. Java.NIO — Selector & Channels
Channel is a lightweight entity effeciently
transporting data between sockets as a tube.
Selector is a manager allowing a single thread to
monitor multiple input channels.
10. Java.IO - Classic IO server design
Server
Socket
Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
12. Java.NIO — NIO server design
ServerSocketChannel channel = ServerSocketChannel.open();
channel.bind(new InetSocketAddress("localhost", 2222));
channel.configureBlocking(false);
Selector selector = Selector.open();
SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
if (selector.select() == 0) {
Thread.sleep(1);
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey selectionKey = keyIterator.next();
if (selectionKey.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (selectionKey.isConnectable()) {
// a connection was established with a remote.
} else if (selectionKey.isReadable()) {
// a channel is ready for reading
} else if (selectionKey.isWritable()) {
// a channel is ready for writing
}
keyIterator.remove();
}
}
14. Java.NIO.2 — Reading
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
// prepare to read
readBuffer.clear();
AsynchronousSocketChannel channel = getChannel2();
channel.read(readBuffer, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
// buffer is ready for read
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
15. Java.NIO.2 — Writing
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
// prepare to put data
writeBuffer.clear();
// putting data
// ...............
// prepare to write
writeBuffer.flip();
AsynchronousSocketChannel channel = getChannel2();
channel.write(writeBuffer, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
// writing has been completed
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
16. Java.NIO — NIO.1 server design
ServerSocketChannel channel = ServerSocketChannel.open();
channel.bind(new InetSocketAddress("localhost", 2222));
channel.configureBlocking(false);
Selector selector = Selector.open();
SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
if (selector.select() == 0) {
Thread.sleep(1);
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey selectionKey = keyIterator.next();
if (selectionKey.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (selectionKey.isConnectable()) {
// a connection was established with a remote.
} else if (selectionKey.isReadable()) {
// a channel is ready for reading
} else if (selectionKey.isWritable()) {
// a channel is ready for writing
}
keyIterator.remove();
}
}
17. Java.NIO — NIO.2 server design
AsynchronousChannelGroup group =
AsynchronousChannelGroup.withThreadPool(newFixedThreadPool(10));
AsynchronousServerSocketChannel channel = open(group);
channel.bind(new InetSocketAddress("localhost", 2222));
channel.accept(null, toHandler((client, attach) -> {
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
client.read(readBuffer, null, toHandler((result, attachment) -> {
// buffer is ready for read
}));
client.write(writeBuffer, null, toHandler((result, attachment) -> {
// writing has been completed
}));
}));
18. public class NetworkServer {
AsynchronousServerSocketChannel channel;
CompletionHandler<AsynchronousSocketChannel, Void> handler;
public NetworkServer(SocketAddress address) throws IOException {
AsynchronousChannelGroup group = withFixedThreadPool(10, Thread::new);
handler = toHandler((channel, attach) -> processAccept(channel));
channel = AsynchronousServerSocketChannel.open(group);
channel.bind(address);
channel.accept(null, toHandler((clientChannel, attach) -> processAccept(clientChannel)));
}
private void processAccept(AsynchronousSocketChannel clientChannel) {
NetworkClient networkClient = new NetworkClient(clientChannel, message ->
out.println("Server: received: " + message));
networkClient.write("Hello! I'm NIO.2 server!n");
channel.accept(null, handler);
}
public void stop() throws IOException {
channel.close();
}
}
Java NIO.2 — Basic implementation of server