Dan*_*Man 2 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();
}
}
Run Code Online (Sandbox Code Playgroud)
这就是结果:
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()
Run Code Online (Sandbox Code Playgroud)
您可以在侦听器中处理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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3358 次 |
| 最近记录: |