yuristry

yuristry

[WIP] Building IM with Netty (Part 1)

  1. 📘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)
    NIO and IO
    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);

The Strongest Java NIO Introduction in History: If you're worried about giving up from the beginning, please read this! - Network Programming/Specialized Technical Area - Instant Messaging Developer Community! (52im.net)

  1. 💡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()
}
  1. 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();
    }
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.