我想创建一个重用通道的连接池,但我不能确定
执行此测试
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();
}我在第二个请求中得到了一个ClosedChannelException (channel.write)....
有没有重用通道的方法?还是保持渠道畅通?
提前感谢
发布于 2012-11-14 08:42:33
第二次写入失败的原因是服务器关闭了连接。
服务器关闭连接的原因是您未能添加HTTP标头
Connection: Keep-Alive添加到原始请求中。
这是为了使通道保持打开状态所必需的(这就是您在此场景中要做的)。
关闭通道后,您必须创建一个新通道。您无法重新打开该频道。Channel.getCloseFuture()返回的ChannelFuture对于通道是最终的(即常量),一旦这个未来的isDone()返回true,它就不能被重置。这就是关闭的通道不能重复使用的原因。
但是,您可以根据需要多次重用打开的通道;但是您的应用程序必须正确地使用HTTP协议才能实现这一点。
https://stackoverflow.com/questions/13368470
复制相似问题