Tiina
Tiina

Reputation: 4765

netty why channel is not yet connected

a client channel is initialized in a server inbound channel channelActive method. And I could see pcap has a 3-way handshake completed (253 is the local host, 15 is the remote one)

packets in pcap

But when writing to the client channel, it throws

java.nio.channels.NotYetConnectedException: null at io.netty.channel.AbstractChannel$AbstractUnsafe.flush0()(Unknown Source)

to my understandings, client channel should be in active state, because a 3-way handshake means the client channel is ready to send packets. But by evaluating clientChannel.isActive(), result is false, weird.

server inbound channel:

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

EDIT: I solved this by adding wait

  f = b.connect(host, port);
  clientChannel = f.channel();
  try {
      f.await(3L, TimeUnit.SECONDS);
      boolean success = clientChannelFuture.isSuccess();

I am not sure if this is appropriate, official proxy example does not have this.

Upvotes: 1

Views: 2383

Answers (1)

Norman Maurer
Norman Maurer

Reputation: 23557

You either need to write via a ChanneFutureListener that you attach to the connect ChannelFuture or you need to sync() / wait() on it.

Remember everything in netty is asynchronous which means when the connect method returns and you trigger the write the Channel may not be fully connected yet.

Upvotes: 3

Related Questions