Netty client handler

package com.star.netty.handler;

import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.util.CharsetUtil;/** * @ClassName ClientHandler * @Author wjp * @Date 2018/7/23 13:43 */public class ClientHandler extends SimpleChannelInboundHandler {

  /**

  * 服务器的连接已经建立之后被调用

  * @param ctx

  * @throws Exception

  */

  @Override

  public void channelActive(ChannelHandlerContext ctx) throws Exception {

    ctx.writeAndFlush(Unpooled.copiedBuffer("netty rocks", CharsetUtil.UTF_8));

    //super.channelActive(ctx);

  }

  /**

  * 处理过程中引发异常时被调用

  * @param ctx

  * @param cause

  * @throws Exception

  */

  @Override

  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    super.exceptionCaught(ctx, cause);

  }

  /**

  * 从服务器中接收到一条消息时被调用

  * @param channelHandlerContext

  * @param byteBuf

  * @throws Exception

  */

  @Override

  protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf)

      throws Exception {

    System.out.println("client received:" + byteBuf.toString(CharsetUtil.UTF_8));

  }

}

你可能感兴趣的:(Netty client handler)