【无标题】

本文介绍了如何使用Netty框架创建一个简单的TCP客户端,包括连接服务端、处理连接成功和失败、粘包分隔以及在通道关闭时进行短线重连的功能。
摘要由CSDN通过智能技术生成

#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();//短线重连
    }
}
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值