Firstly, there are several problems with the sent HTTP message: each line of the HTTP message is split / ends with CR LF, and not just a line feed (although I doubt this could be a problem, you should replace "\ n" with "\ r \ n "). In addition, the Content-Length is not equal to the actual size of the message body to be replaced. Before the actual body, all HTTP messages should have an empty string that you do not have. Finally, the forward slash in <html/> should also appear before html , for example: </html>
Summarizing:
bufferedWriter.write("HTTP/1.0 200 OK\r\nDate: Fri, 31 Dec 1999 23:59:59 GMT\r\nContent-Type: text/html\r\nContent-Length:18\r\n\r\n<html>abcde</html>");
Now for the real problem: the read loop was constantly expecting more data. Comparing the readLine () result with zero does not actually do what you were looking for. TCP connections create data streams, and you never know if the client simply stopped sending data at a certain point. Instead, you can read until you find a blank line that marks the end of the header of the HTTP message. Web browsers usually do not send additional content to GET messages, so you will not be missing any data.
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); while(!(line = reader.readLine()).isEmpty()){ System.out.println(line); }
source share