나는 Socket을 사용하여 자바로 매우 원시 웹 서버를 만드는 책에서 운동을하고있다. 나는 브라우저가 localhost : 8080을 가리킬 때를 제외하고 나는 모든 것이 작동한다고 믿는다. 응답에 헤더가 포함되어있다. 브라우저의 응답은 다음과 같습니다text/plain 헤더를 볼 수 있습니까?
HTTP/1.1 200 Ok
content-type: text/plain; charset=UTF-16
content-length: 50
date: Sat, 22 Feb 2014 01:21:50 GMT
Success!! You connected.
응답을 생성하는 내 코드는 다음과 같습니다
private static final String HTTP_VALID = "HTTP/1.1";
private static final String METHOD_GET = "GET";
private static final String ENCODING = "UTF-16";
private static final String CONTENT_TYPE = "Content-Type: text/plain; charset=" + ENCODING;
private static final String CONTENT_LENGTH = "Content-Length: ";
private static final String DATE = "Date: ";
private void issueResponse(String dir, boolean success) throws IOException
{
try (BufferedWriter buf = new BufferedWriter
(new OutputStreamWriter(clientSocket.getOutputStream(), ENCODING)))
{
String statusCode = null;
String statusResponse = null;
String message = null;
if (success)
{
statusCode = "200";
statusResponse = "Ok";
message = "Success!! You connected.";
}
else
{
statusCode = "404";
statusResponse = "Not Found";
message = "Failure, resource not found.";
}
long cLength = message.getBytes(ENCODING).length;
int l = message.length();
String now = generateDate();
buf.write(HTTP_VALID + " " + statusCode + " " + statusResponse);
buf.write(System.lineSeparator());
buf.write(CONTENT_TYPE);
buf.write(System.lineSeparator());
buf.write(CONTENT_LENGTH + cLength);
buf.write(System.lineSeparator());
buf.write(DATE + now);
buf.write(System.lineSeparator());
buf.write(System.lineSeparator());
buf.write(message);
buf.flush();
}
}
내가 같은 브라우저에서 헤더를 볼 수있을 경우, 또는 내가 뭔가를 할 않았다
잘못된?업데이트 : 다음은 텔넷 세션의 결과입니다. 헤더 앞에 가비지 문자가있는 것 같습니다. 어떤 원인이 될 수 있습니까?
[email protected] ~
$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET/HTTP/1.1
▒HTTP/1.1 200 Ok
Content-Type: text/plain; charset=UTF-16
Content-Length: 50
Date: Sat, 22 Feb 2014 01:37:56 GMT
Success!! You connected.Connection closed by foreign host.
업데이트 - 인코딩이 UTF-8로 변경되고 가비지 문자가없는 이유는 무엇입니까?
헤더가 이미 브라우저에 의해 소비 된 것으로 보인다 : 제대로 일 경우 콘솔 클라이언트를 통해 서버 포트에 연결합니다 (새로운 라인을 참고) 경우
이 출력해야한다. 'telnet localhost 8080'을 시도해보고 나서'GET HTTP/1.0'과 2 개의 캐리지 리턴을 보낼 수 있습니다. 서버 응답을 볼 수 있습니다. 두 번째 줄 바꿈 후에 더 이상 헤더를 사용할 수 없습니다. – helderdarocha