Netty(二)建立客户端

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014252478/article/details/82796380

1、建立的工程目录如下:

  

2、客户端:

(1)客户端时序图

(2)编码流程

  1. 创建Bootstrap实例
  2. 设置EventLoop
  3. 指定Channel类型
  4. option配置
bootstrap = new Bootstrap();
eventLoopGroup = new NioEventLoopGroup();       
bootstrap.group(eventLoopGroup)
         .channel(NioSocketChannel.class)
         .option(ChannelOption.SO_KEEPALIVE, true);
    
  1. 指定Handler
  2. connect
public void connectServer() throws InterruptedException {
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel sc) throws Exception {
                sc.pipeline()
                        .addLast(new ProtocolDecoder(chargeDevice))
                        .addLast(new ProtocolEncoder())
                        .addLast(new IdleStateHandler(readerIdleTime, writerIdleTime, allIdleTime, TimeUnit.SECONDS))
                        .addLast(new MyInboundHandler(chargeDevice));
            }
        });
        this.channelFuture = bootstrap.connect().sync();
    }

关闭:close()

public void close() throws InterruptedException {
        try {
            this.channelFuture.channel().close().sync();
        } finally {
            this.channelFuture.channel().eventLoop().shutdownGracefully();
        }
    }

message数据写出:

public void writeMessage(Message msg) {
        if (this.channelFuture == null || this.channelFuture.channel().isActive() == false) {
            log.info("inactive connection, can not write message.");
            return;
        }
        channelFuture.channel().writeAndFlush(msg);
    }

客户端的主要流程就是这样了,记录一下。

猜你喜欢

转载自blog.csdn.net/u014252478/article/details/82796380
今日推荐