如何在netty通道池中读取服务器响应?

时间:2015-06-12 05:24:23

标签: java netty

我在客户端使用通道池API连接到服务器。当我向服务器发送请求时,它接受&成功地完成了它,但当服务器回复时,我的客户端没有获得该数据。

客户频道池

group = new NioEventLoopGroup();
final Bootstrap b = new Bootstrap();
b.group(group)
  .channel(NioSocketChannel.class)
  .option(ChannelOption.SO_KEEPALIVE, true)
  .handler(new ClientInitializer());

poolMap = new AbstractChannelPoolMap<InetSocketAddress, SimpleChannelPool>() {

@Override
protected SimpleChannelPool newPool(InetSocketAddress key) {
  return new SimpleChannelPool(b.remoteAddress(key), new SimpleChannelPoolHandler());
}
};

ClientInitializer

private static final StringDecoder DECODER = new StringDecoder();
private static final StringEncoder ENCODER = new StringEncoder();

private static final ClientHandler CLIENT_HANDLER = new ClientHandler();

@Override
public void initChannel(SocketChannel ch)
{
  ChannelPipeline pipeline = ch.pipeline();

  // Add the text line codec combination first,
  pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
  pipeline.addLast(DECODER);
  pipeline.addLast(ENCODER);

  // and then business logic.
  pipeline.addLast(CLIENT_HANDLER);
}

ClientHandler的

public class ClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        System.out.println(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

使用频道池向服务器发送数据:

final SimpleChannelPool pool = Client.poolMap.get(addr);

        Future<Channel> f = pool.acquire();

        f.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(Future<Channel> f) {

                if (f.isSuccess()) {

                    Channel ch = f.getNow();

                    ChannelFuture lastWriteFuture = null;
                    try {

                        lastWriteFuture = ch.writeAndFlush(my data here;


                         // Wait until all messages are flushed before closing the channel.
                        if (lastWriteFuture != null) {

                            lastWriteFuture.sync();
                        }
                    } catch (JsonProcessingException | InterruptedException e) {

                        e.printStackTrace();
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    // Release back to pool
                    pool.release(ch);
                }
            }

        });

如果我不使用频道池那么所有工作都很好&amp;我在ClinetHandler类中得到了正确的响应。

我在打破什么建议吗?

我正在使用Netty 4.0.28 final。

1 个答案:

答案 0 :(得分:2)

我在#netty IRC频道上得到了答案

所以我需要删除这一行

.handler(new ClientInitializer());

无论我的ClientInitializer在做什么,我都需要在SimpleChannelPoolHandler channelCreated方法中这样做。