欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

关于netty的疑惑

程序员文章站 2022-03-02 15:25:36
...
应用场景为 android中使用netty,android关闭无线、gprs,然后随便连接一个ip地址,部分代码

bootstrap.setOption("keepAlive", true);
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("connectTimeoutMillis", CONNECT_TIMEOUT);

// 向目标地址发起一个连接
ChannelFuture connectFuture = bootstrap.connect(inetSocketAddress);

session = connectFuture.awaitUninterruptibly().getChannel();

Log.i("re", "connectFuture.isSuccess()=" + connectFuture.isSuccess());
Log.i("re", "connectFuture.isConnected()=" + session.isConnected());
if (session.isConnected()) {
businessListener.onServerConnected();
} else {
businessListener.onServerNetWorkError();
}

竟然 session.isConnected()为true。
打开无线或者gprs,就变得正常,为什么在没人任何网络的情况下session.isConnected()为true呢?
handler代码

private class MinaClientHandler extends SimpleChannelHandler {

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
String theMessage = (String) e.getMessage();
JSONObject commandJsonObject = new JSONObject(theMessage);
businessListener.onReceive(commandJsonObject);
}

public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
Log.i("re", "channelConnected");
}

@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
Log.i("re", "channelDisconnected");
}

@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
Log.i("re", "channelClosed");
}

public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
Throwable cause = e.getCause();
cause.printStackTrace();
// if (cause instanceof SocketException) {
// ctx.getChannel().close();
// }
Log.i("re", "exceptionCaught");
}
}

没有任何网络的情况下,handler的 channelConnected channelDisconnected channelClosed 正常调用,不明白netty为什么这样处理,这样就造成当没有任何网络的的情况下,就不能通过session.isConnected()来判断是否连接成功。
相关标签: netty