- 📘Basic Knowledge: NIO and IO
Cut the nonsense! Understand the difference between Java's NIO and classic IO in one minute - Network Programming/Specialized Technical Area - Instant Messaging Developer Community! (52im.net)
IO reads data from blocking streams
InputStream input = ... ;
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
NIO
Depends on Channel and buffer, Channel is bidirectional for reading and writing, different from the subclasses of InputStream and OutputStream in IO;
ByteBuffer buffer = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buffer);
// Check if the buffer has enough data written for processing
while (! bufferFull(bytesRead) ) {
bytesRead = inChannel.read(buffer);
}
e.g. (1) First get the channel from FileInputStream (2) Then create a buffer (3) Read data from the channel to the buffer
FileInputStream fin = new FileInputStream("demo.txt");
FileChannel fc = fin.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);`
fc.read(buffer);
- 💡netty's ChannelHandler component, used to handle various events of the Channel;
@Override
protected void initChannel(Channel ch) {
ChannelPipeline channelPipeline = ch.pipeline();
// ChannelHandler chain
channelPipeline.addLast()
}
- ChannelInboundHandlerAdapter
Inherit from the ChannelInboundHandlerAdapter class and implement a special Channel handler
@Override
public void channelActive(ChannelHandlerContext ctx) {
// Add to the manager
channelManager.add(ctx.channel());
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) {
// Remove from the manager
channelManager.remove(ctx.channel());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.error("[exceptionCaught][Exception occurred in connection ({})]", ctx.channel().id(), cause);
// Disconnect
ctx.channel().close();
}