版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014252478/article/details/82796380
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);
}
客户端的主要流程就是这样了,记录一下。