Netty 4.0.x正确捕获ConnectException

时间:2014-05-26 19:26:59

标签: java netty connectexception

我正在使用Netty开发一个应用程序,我需要在客户端处理ConnectException,以防万一,例如,连接超时。

这是代码

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;

public class ConnectTest {

public static void main(String[] args) throws Exception {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {

        }
    });
    final ChannelFuture f = b.connect("0.0.0.0", 8080);
    f.addListener(new FutureListener<Void>() {

        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!f.isSuccess())
                System.out.println("Test Connection failed");
        }
    });
    f.sync();
}
}

这就是结果:     

        Test Connection failed
        Exception in thread "main" 
    java.net.ConnectException: Connection refused: no further information: /0.0.0.0:8080
        at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
        at sun.nio.ch.SocketChannelImpl.finishConnect(Unknown Source)
        at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:208)
        at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:287)
        at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:524)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:378)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:350)
        at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
        at java.lang.Thread.run(Unknown Source)

正如你所看到的那样,监听器工作正常,但我仍然打印出一个难看的堆栈跟踪,我无法弄清楚拦截它的位置。

任何提示?

1 个答案:

答案 0 :(得分:5)

罪魁祸首是

f.sync() 

您可以在侦听器中处理ConnectExceptions:

    final ChannelFuture f = b.connect("0.0.0.0", 8080);
    f.addListener(new FutureListener<Void>() {

        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!f.isSuccess()) {
                System.out.println("Test Connection failed");
                handleException(future.cause());

            }
        }
    });
    //f.sync();