1. 程式人生 > >Netty(二)建立客戶端

Netty(二)建立客戶端

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);
    }

客戶端的主要流程就是這樣了,記錄一下。