【问题标题】:Getting a ConnectionClosedException with Http.Core talking to Http.Client 4?使用 Http.Core 与 Http.Client 4 交谈时获得 ConnectionClosedException?
【发布时间】:2014-08-13 09:01:05
【问题描述】:

我正在尝试使用 http.core 和客户端 4.3。总的来说,它运作良好,并且处理起来非常愉快。但是,我的一次转账收到了ConnectionClosedException,我不明白为什么。据我所知,其他人工作得很好。

一切都以非常直接的方式遵循示例。如果没有,它会被尽可能多地重写以消除这种情况。

  1. 有 2 台服务器,都运行相同的代码 [A 和 B]
  2. A HttpClient 向 B 发送请求“AX”(POST)
  3. B HttpService 收到“AX”帖子,对其进行处理
  4. B HttpClient 在不同的端口上向 A 发送回复“BR”(POST)
    1. 稍后这应该在与 A 的连接关闭后发生,或尽可能关闭
    2. 现在代码实际上并不关心
  5. A 收到 B 的回复(在不同的线程上)并做事

在问题场景中,A 作为服务器运行,B 正在发送 POST。抱歉,这并不总是很清楚,因为在一个事务中,双方最终都会运行服务器和客户端代码。

  1. A 向 B:8080 发送 POST。在线获取正确的响应,一切正常。
  2. 与 B:8080 的 POST 连接正确关闭
  3. B 向 A 发送新的 POST(如 ACK)(例如... B:53991 => A:9000强>)。
    1. A 处理一切。没有问题
    2. A rasies ConnectionClosedException

由于我不确定为什么会发生这种情况,因此我尝试将我认为相关的所有内容都放在那里。我现在唯一的想法是它与确保我添加/更改连接控制标头有关,但我看不出这会如何影响任何事情。

堆栈跟踪来自机器“A”,当来自 B 的回复时

org.apache.http.ConnectionClosedException: Client closed connection
    at org.apache.http.impl.io.DefaultHttpRequestParser.parseHead(DefaultHttpRequestParser.java:133)
    at org.apache.http.impl.io.DefaultHttpRequestParser.parseHead(DefaultHttpRequestParser.java:54)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:260)
    at org.apache.http.impl.DefaultBHttpServerConnection.receiveRequestHeader(DefaultBHttpServerConnection.java:131)
    at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:307)
    at com.me.HttpRequestHandlerThread.processConnection(HttpRequestHandlerThread.java:45)
    at com.me.net.http.HttpRequestHandlerThread.run(HttpRequestHandlerThread.java:70)
com.me.ExceptionHolder: Client closed connection
    at com.me.log.Log.logIdiocy(Log.java:77)
    at com.me.log.Log.error(Log.java:54)
    at com.me.net.http.HttpRequestHandlerThread.run(HttpRequestHandlerThread.java:72)
Caused by: org.apache.http.ConnectionClosedException: Client closed connection
    at org.apache.http.impl.io.DefaultHttpRequestParser.parseHead(DefaultHttpRequestParser.java:133)
    at org.apache.http.impl.io.DefaultHttpRequestParser.parseHead(DefaultHttpRequestParser.java:54)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:260)
    at org.apache.http.impl.DefaultBHttpServerConnection.receiveRequestHeader(DefaultBHttpServerConnection.java:131)
    at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:307)
    at com.me.net.http.HttpRequestHandlerThread.processConnection(HttpRequestHandlerThread.java:45)
    at com.me.net.http.HttpRequestHandlerThread.run(HttpRequestHandlerThread.java:70)

这是运行在 B(本场景中的“客户端”)上的代码。它正在尝试 POST 确认正确收到来自 A 的第一个 POST 的回复。确实没有什么要传输的,响应应该只是一个 HTTP 200:

try (CloseableHttpClient client = HttpClients.createDefault()) {
    final HttpPost post = new HttpPost(url);
    post.setHeaders(/* create application specific headers */);

    ByteArrayEntity entity = new ByteArrayEntity(IOUtils.toByteArray(myStream));
    post.setEntity(entity);

    ResponseHandler<Void> responseHandler = new ResponseHandler<Void>() {
        @Override
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine status = response.getStatusLine();
            if (!NetUtil.isValidResponseCode(response)) {
                throw new ClientProtocolException("Unexpected Error! Oops");
            }
            // consume the response, if there is one, so the connection will close properly
            EntityUtils.consumeQuietly(response.getEntity());
            return null;
        }
    };

    try {
        client.execute(post, responseHandler);
    } catch (ClientProtocolException ex) { 
        // logic to queue a resend for 10 minutes later.  not triggered
        throw ex;
    }
}

On A:这称为异步,因为响应不是通过同一个 http 连接进来的。

主请求处理程序做了很多工作,但令人惊讶的是,在处理程序/服务器端实际控制 HTTP 的代码却很少。伟大的图书馆......我以某种方式滥用。这是实际的处理程序,一切都简化了一点,删除了验证等。

public class AsyncReceiverHandler implements HttpRequestHandler {

    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
        // error if not post, other logic.  not touching http.  no errors
        DefaultBHttpServerConnection connection = (DefaultBHttpServerConnection) context.getAttribute("connection");
        Package pkg = NetUtil.createPackageFrom(connection); // just reads sender ip/port
        NetUtil.copyHttpHeaders(request, pkg); 
        try {
            switch (recieive(request, pkg)) {
                case EH_OK:
                    response.setStatusCode(HttpStatus.SC_OK);
                    break;
                case OHNOES_BAD_INPUT:
                    response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
                    response.setEntity(new StringEntity("No MDN entity found in request body"));
                // bunch of other cases, but are not triggered.  xfer was a-ok
            }
        } catch (Exception ex) {
            //log
        } 
    }
    private MyStatus receiveMdn(HttpRequest request, Package pkg) throws Exceptions..., IOException {
        // validate request, get entity, make package, no issues
        HttpEntity resEntity = ((HttpEntityEnclosingRequest) request).getEntity();

        try {
            byte[] data = EntityUtils.toByteArray(resEntity);
            // package processing logic, validation, fairly quick, no errors thrown
        } catch (Exceptions... ex) {
            throw ExceptionHolder(ex);
        }
    }
}

这是请求处理线程。这和服务器几乎是从样本中逐字提取的。服务处理程序只是启动服务和accept()s 套接字。当它得到一个时,它会创建一个新的副本,并调用 start():

public HttpRequestHandlerThread(final HttpService httpService, final HttpServerConnection conn, HttpReceiverModule ownerModule) {
        super();
        this.httpService = httpService;
        this.conn = (DefaultBHttpServerConnection) conn;
    }
    private void processConnection() throws IOException, HttpException {
        while (!Thread.interrupted() && this.conn.isOpen()) {
            /* have the service create a handler and pass it the processed request/response/context */
            HttpContext context = new BasicHttpContext(null);
            this.httpService.handleRequest(this.conn, context);
        }
    }
    @Override
    public void run() {
        // just runs the main logic and reports exceptions. 
        try {
            processConnection();
        } catch (ConnectionClosedException ignored) {
            // logs error here (and others). 
        } finally {
            try { this.conn.shutdown(); } catch (IOException ignored) {}
        }
    }
}

【问题讨论】:

  • SO 是此类问题的错误场所。您能否在 GitHub(或类似网站)上提供您的代码并将您的问题发布到 httpclient-users@hc.apache.org 或 dev@hc.apache.org?
  • @oleg。 SO 是解决此类问题的绝佳场所。我会说这是有SO的原因!邮件列表很痛苦,但也许它们是这些天 l337 hax0rs 闲逛的地方,所以我需要再次检查它们;)以及为什么任何人会让他们的代码可用我>给你?如果不是他们的代码,而是雇主的代码怎么办。说真的,你不能在这个 oleg 中变得那么新。
  • 也许我错过了它,但是 B 打开与 A 的连接的代码在哪里?此外,您在哪台机器(A 或 B)上看到堆栈跟踪。
  • 对不起@WarrenDew,我意识到现在有点不清楚......堆栈跟踪来自机器A。在这种情况下,“客户端”是“B”,接收服务器是“A”。我看看能不能改写问题
  • @Andrew Backer:适合自己。

标签: java sockets java-7 apache-httpclient-4.x apache-httpcomponents


【解决方案1】:

嗯,现在看来这很愚蠢,而且非常明显。我暂时忽略了这个问题,然后转移到其他事情上,答案从潜意识中冒出来,就像他们一样。

我把这个标题加回去了,一切都清楚了:

post.setHeader("Connection", "close, TE")

不知何故,设置Connection 标头的行被我删除了,可能是我不小心删除的。他们中的很多都设置好了,它仍然存在,只是在这个代码路径中出错了。基本上,服务器希望此连接立即关闭,但标头恢复为默认的keep-alive。由于客户端在完成连接后立即关闭连接,这让服务器感到惊讶,服务器被告知,并且正确地遵守了:D 在反向路径中一切正常。

由于我刚刚将旧堆栈更改为使用HttpComponents,因此我没有查看标题等,我只是假设我使用错误。老栈不介意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-31
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多