Introduction to Netty (3) Components

  This section focuses on the components of Netty.

1. Channel

  It represents an open connection for connecting to an entity such as a hardware device, file, network socket, or program component capable of performing one or more different I/O operations . Can be likened to a transfer tool for incoming and outgoing data.

 

2. Callback (callback)

  It is a method that is given to another method as a reference so that the latter can call the former at some suitable time. For example the following code:

1  public  class DiscardServerHandler extends ChannelInboundHandlerAdapter {
 2      
3      /** 
4       * Called when data is received
 5       */ 
6      @Override
 7      public  void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
 8          // TODO data processing 
9      }
 10 }

  When the server receives a message, the ChannelRead method is automatically called, so we can override this method to handle the received data.

 

三、Future

  It provides another way to notify the application that an operation has completed. Each Netty outbound (outbound) I/O operation will return a ChannelFuture, which allows one or more ChannelFutureListener instances, the callback method operationComplete() will be called when the operation is completed, the following is the sample code:

1  // Start the client, the client connects with connect 
2 ChannelFuture f = b.connect(host, port).sync();
 3 f.addListener( new ChannelFutureListener() {    
 4      public  void operationComplete(ChannelFuture future) throws Exception {    
 5          if (future.isSuccess()) {         // The connection is successful 
6              ByteBuf buf = Unpooled.copiedBuffer("hello",              // write data 
7                      Charset.defaultCharset());
 8              ChannelFuture wf = future.channel().writeAndFlush( buf);     // send data
 9         } else {
10             // 打印错误
11             Throwable cause = future.cause();
12             cause.printStackTrace();
13         }
14     }
15 });

 

  The above code first connects to the remote address, when the connection is complete, checks the connection status, if successful, hello is sent, otherwise an error is thrown.

 

4. Event and Handler

  I don't understand, I'll fix it later.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326522446&siteId=291194637