Netty(二)建立客戶端
阿新 • • 發佈:2018-11-02
1、建立的工程目錄如下:
2、客戶端:
(1)客戶端時序圖:
(2)編碼流程:
- 建立Bootstrap例項
- 設定EventLoop
- 指定Channel型別
- option配置
bootstrap = new Bootstrap(); eventLoopGroup = new NioEventLoopGroup(); bootstrap.group(eventLoopGroup) .channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true);
- 指定Handler
- 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); }
客戶端的主要流程就是這樣了,記錄一下。