首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >netty重用通道

netty重用通道
EN

Stack Overflow用户
提问于 2012-11-14 04:43:49
回答 1查看 3K关注 0票数 3

我想创建一个重用通道的连接池,但我不能确定

执行此测试

代码语言:javascript
复制
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)....

有没有重用通道的方法?还是保持渠道畅通?

提前感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-14 08:42:33

第二次写入失败的原因是服务器关闭了连接。

服务器关闭连接的原因是您未能添加HTTP标头

代码语言:javascript
复制
Connection: Keep-Alive

添加到原始请求中。

这是为了使通道保持打开状态所必需的(这就是您在此场景中要做的)。

关闭通道后,您必须创建一个新通道。您无法重新打开该频道。Channel.getCloseFuture()返回的ChannelFuture对于通道是最终的(即常量),一旦这个未来的isDone()返回true,它就不能被重置。这就是关闭的通道不能重复使用的原因。

但是,您可以根据需要多次重用打开的通道;但是您的应用程序必须正确地使用HTTP协议才能实现这一点。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13368470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档