Frage

i want to create a connection pool that reuse channels but i couldn't figure out

executing this test

public void test() {


    ClientBootstrap client = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    client.setPipelineFactory(new ClientPipelineFactory());

    // Connect to server, wait till connection is established, get channel to write to
    Channel channel = client.connect(new InetSocketAddress("192.168.252.152", 8080)).awaitUninterruptibly().getChannel();
    {
        // Writing request to channel and wait till channel is closed from server
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "test");

        String xml = "xml document here";
        ChannelBuffer buffer = ChannelBuffers.copiedBuffer(msgXml, Charset.defaultCharset());
        request.addHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes());
        request.addHeader(HttpHeaders.Names.CONTENT_TYPE, "application/xml");
        request.setContent(buffer);

        channel.write(request).awaitUninterruptibly().getChannel().getCloseFuture().awaitUninterruptibly();

        channel.write(request).awaitUninterruptibly().getChannel().getCloseFuture().awaitUninterruptibly();
    }
    client.releaseExternalResources();

}

I got an ClosedChannelException in the second channel.write(request)....

Exist a way to reuse the channels? or remain the channel open?

thanks in advance

War es hilfreich?

Lösung

The reason the second write failed is because the server closed the connection.

The reason the server closed the connection is because you failed to add the HTTP header

Connection: Keep-Alive

to the original request.

This is required in order to leave the channel open (which is what you want to do in this scenario).

Once a channel has been closed, you must create a new channel. You cannot reopen the channel. The ChannelFuture returned by Channel.getCloseFuture() is final (i.e., constant) to the channel and once isDone() on this future returns true it cannot be reset. This is the reason that a closed channel cannot be reused.

However, you may reuse an open channel as many times as you need; but your application must talk the HTTP protocol properly in order to accomplish this.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top