Java, sockets, BufferedReader, and readline hang … :(

后端 未结 3 1239
半阙折子戏
半阙折子戏 2020-12-03 19:12

I\'m not a Java programmer at all. I try to avoid it at all costs actually, but it is required that I use it for a class (in the school sense). The teacher requires that w

相关标签:
3条回答
  • 2020-12-03 19:35

    So you're reading from a socket (you don't show that in your code, but that's what I gather from the text)?

    As long as the other side is not closing the connection, Java doesn't know that it's at the end of the input, so readLine() is waiting for the other side to send more data and doesn't return null.

    0 讨论(0)
  • 2020-12-03 19:39

    Your HTTP request is not complete without 2 carriage return + linefeed pairs. You should probably also call close after the request is sent:

    out.print("GET /index.html HTTP/1.0\r\n");
    // maybe print optional headers here
    // empty line
    out.print("\r\n");
    out.flush();
    out.close();
    
    0 讨论(0)
  • 2020-12-03 19:56

    Your problem is the content encoding “chunked”. This is used when the length of the content requested from the web server is not known at the time the response is started. It basically consists of the number of bytes being sent, followed by CRLF, followed by the bytes. The end of a response is signalled by the exact sequence you are seeing. The web server is now waiting for your next request (this is also called “request pipelining”).

    You have several possibilities:

    • Use HTTP version 1.0. This will cause the webserver to automatically close the connection when a response has been sent completely.
    • Specify the “Connection: close” header when sending your request. This will also close the connection.
    • Parse content encoding “chunked” correctly and simply treat this as if the response is now complete—which it is.
    0 讨论(0)
提交回复
热议问题