anhurry
11/19/2019 - 6:54 AM

Netty basic client.java

@Slf4j
public class NettyClient {
    private static final int MAX_RETRY = 5;

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.attr(AttributeKey.newInstance("clientNamne"), "nettyClient");
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY,true);
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                });
        connect(bootstrap, "127.0.0.1", 1024, MAX_RETRY);
    }

    private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
        bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                log.info("连接成功");
                ChannelFuture channelFuture = (ChannelFuture)future;
                Channel channel = channelFuture.channel();
                while (true) {
                    channel.writeAndFlush(new Date() + ": hello world!");
                    Thread.sleep(2000);
                }
            } else if (retry == 0) {
                log.info("重连次数已用完, 放弃连接");
            } else {
                int order = (MAX_RETRY - retry) + 1;
                int delay = 1 << order;
                log.error("连接失败, {} 秒后, 第{}次重连...", delay, order);
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
            }
        });
    }

}