netty 为什么频道还没有连接
netty why channel is not yet connected
客户端通道在服务器入站通道 channelActive
方法中初始化。我可以看到 pcap 完成了 3 次握手(253 是本地主机,15 是远程主机)
但是当写入客户端通道时,它会抛出
java.nio.channels.NotYetConnectedException: null at
io.netty.channel.AbstractChannel$AbstractUnsafe.flush0()(Unknown
Source)
根据我的理解,客户端通道应该处于活动状态,因为 3 次握手意味着客户端通道已准备好发送数据包。但是通过评估clientChannel.isActive(),结果是错误的,很奇怪。
服务器入站通道:
Channel clientChannel;
@Override
public void channelActive(ChannelHandlerContext ctx) {
final Channel inboundChannel = ctx.channel();
try {
Bootstrap b = new Bootstrap();
b.group(inboundChannel.eventLoop())
.channel(inboundChannel.getClass())
.handler(new SomeClientChannelInitializer(ctx));
// Make the connection attempt.
ChannelFuture f = b.connect(host, port);
clientChannel = f.channel();
} catch (Exception e) {// no exception}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.info("receive: {}", msg);
clientChannel.writeAndFlush(msg -> this::pojo);
}
编辑:
我通过添加 wait
解决了这个问题
f = b.connect(host, port);
clientChannel = f.channel();
try {
f.await(3L, TimeUnit.SECONDS);
boolean success = clientChannelFuture.isSuccess();
我不确定这样是否合适,官方代理示例没有这个。
您要么需要通过附加到连接 ChannelFuture
的 ChanneFutureListener
写入,要么需要在其上 sync()
/ wait()
。
记住 netty 中的所有内容都是异步的,这意味着当 connect
方法 returns 并且您触发 write
时 Channel
可能尚未完全连接。
客户端通道在服务器入站通道 channelActive
方法中初始化。我可以看到 pcap 完成了 3 次握手(253 是本地主机,15 是远程主机)
但是当写入客户端通道时,它会抛出
java.nio.channels.NotYetConnectedException: null at io.netty.channel.AbstractChannel$AbstractUnsafe.flush0()(Unknown Source)
根据我的理解,客户端通道应该处于活动状态,因为 3 次握手意味着客户端通道已准备好发送数据包。但是通过评估clientChannel.isActive(),结果是错误的,很奇怪。
服务器入站通道:
Channel clientChannel;
@Override
public void channelActive(ChannelHandlerContext ctx) {
final Channel inboundChannel = ctx.channel();
try {
Bootstrap b = new Bootstrap();
b.group(inboundChannel.eventLoop())
.channel(inboundChannel.getClass())
.handler(new SomeClientChannelInitializer(ctx));
// Make the connection attempt.
ChannelFuture f = b.connect(host, port);
clientChannel = f.channel();
} catch (Exception e) {// no exception}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.info("receive: {}", msg);
clientChannel.writeAndFlush(msg -> this::pojo);
}
编辑:
我通过添加 wait
f = b.connect(host, port);
clientChannel = f.channel();
try {
f.await(3L, TimeUnit.SECONDS);
boolean success = clientChannelFuture.isSuccess();
我不确定这样是否合适,官方代理示例没有这个。
您要么需要通过附加到连接 ChannelFuture
的 ChanneFutureListener
写入,要么需要在其上 sync()
/ wait()
。
记住 netty 中的所有内容都是异步的,这意味着当 connect
方法 returns 并且您触发 write
时 Channel
可能尚未完全连接。