#netty tcp client的简单实现(实现简单的与服务端连接,收信处理、短线重连及粘包分隔符)
1.NettyClient 实现连接服务端及短线重连
public class NettyClient {
private static final int MAX_RETRY = 1000;
private static final String HOST = "127.0.0.1";
private static final int PORT = 13300;
@Autowired
private static SystemProperties systemProperties;
public NettyClient(){
this.systemProperties = SpringContextUtil.getBean(SystemProperties.class);
}
public static void startClient() {
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap
.group(workerGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
// 空闲检测
// ch.pipeline().addLast(new IMIdleStateHandler());
//粘包
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
// ch.pipeline().addLast(new ByteToChatMessageDecoder());
ch.pipeline().addLast(new StringDecoder()); //加載解碼器
ch.pipeline().addLast(new StringEncoder()); //加載編碼器
ch.pipeline().addLast(new ChannelActiveHandler());
}
});
connect(bootstrap, HOST, PORT, MAX_RETRY,systemProperties);
}
private static void connect(Bootstrap bootstrap, String host, int port, int retry, SystemProperties systemProperties) {
bootstrap.connect(host, port).addListener(future -> {
if (future.isSuccess()) {
System.out.println(new Date() + ": 连接成功,启动控制台线程……");
Channel channel = ((ChannelFuture) future).channel();
//startConsoleThread(channel);
} else if (retry == 0) {
System.err.println("重试次数已用完,放弃连接!");
} else {
// 第几次重连
int order = (MAX_RETRY - retry) + 1;
// 本次重连的间隔
// int delay = 1 << order;
System.err.println(new Date() + ": 连接失败,第" + order + "次重连……");
bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1,systemProperties), 5, TimeUnit
.SECONDS);
}
});
}
}
2.ChannelActiveHandler 实现活跃或离线处理
@ChannelHandler.Sharable
@Slf4j
public class ChannelActiveHandler extends ChannelInboundHandlerAdapter {
@Autowired
private static SystemProperties systemProperties;
/**
* 有客户端连接服务器会触发此函数
*/
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("与服务端连接成功");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg){
System.out.println("接收到的内容为"+msg.toString());
//下面可以实现具体的逻辑
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
System.out.println("断开");
ctx.fireChannelInactive();
NettyClient.startClient();//短线重连
}
}