Trouble sending HTTP response with Java Socket

前端 未结 4 1617
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 00:55

I\'ve been trying to write the beginnings of a simple web server, but can\'t seem to get the response to get sent. I\'ve tried every type of Output stream imaginable but no

4条回答
  •  耶瑟儿~
    2021-01-14 01:37

    I've been struggling like crazy with a very similar issue.

    After literally head-banding on the wall I found my issue was so trivial I kept on head-banging on the wall for a while.

    Basically in my input while loop I was checking for a null line, but I forgot to check for an empty line (and subsequently break).

    No guarantee it'll work the same for you but here's my one cent:

    in = session.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String line = null;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
        // this seems to be the key for me! 
        // somehow I never get out of this loop if I don't 
        // check for an empty line...
        if (line.isEmpty()) {
            break;
        }
    }
    out = new BufferedWriter(
        new OutputStreamWriter(
            new BufferedOutputStream(session.getOutputStream()), "UTF-8")
    );
    out.write(OUTPUT_HEADERS + OUTPUT.length() + OUTPUT_END_OF_HEADERS + OUTPUT);
    out.flush();
    out.close();
    session.close();
    

    My constants are:

    private static final String OUTPUT = "Example

    Worked!!!

    "; private static final String OUTPUT_HEADERS = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: "; private static final String OUTPUT_END_OF_HEADERS = "\r\n\r\n";

    My "session" variable is a Socket object.

提交回复
热议问题