Netty:ClientBootstrap 连接重试

Pau*_*lgo 3 java netty

我需要连接到服务器,我知道该服务器将在端口上侦听。尽管可能需要一些时间才能投入运营。是否可以让 ClientBootstrap 尝试连接给定的尝试次数或直到达到超时?

目前,如果连接被拒绝,我会收到异常,但它应该尝试在后台连接,例如通过尊重“connectTimeoutMillis”引导选项。

Nor*_*rer 5

你需要手动完成,但这并不难..

你可以这样做:

final ClientBootstrap bs = new ClientBootstrap(...);
final InetSocketAddress address = new InetSocketAddress("remoteip", 110);
final int maxretries = 5;
final AtomicInteger count = new AtomicInteger();
bs.connect(address).addListener(new ChannelFutureListener() {

    public void operationComplete(ChannelFuture future) throws Exception {
        if (!future.isSuccess()) {
            if (count.incrementAndGet() > maxretries) {
                // fails to connect even after maxretries do something
            } else {
                // retry
                bs.connect(address).addListener(this);
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)