gpt4 book ai didi

java - Netty 4.0.x 正确捕获 ConnectException

转载 作者:行者123 更新时间:2023-11-30 06:18:56 26 4
gpt4 key购买 nike

我正在使用 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)

如您所见,监听器工作正常,但我仍然打印出丑陋的堆栈跟踪信息,但我不知道在哪里拦截它。

有什么提示吗?

最佳答案

罪魁祸首是

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();

关于java - Netty 4.0.x 正确捕获 ConnectException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23876564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com