들어가기
지난 포스팅에선 Http 요청 메세지의 가장 마지막에 EOF가 없어 bufferedReader.readline()이 무한 대기 상태에 빠졌었다.
EOF는 클라이언트의 연결이 종료돼야 날아오기 때문에 EOF를 기준으로 body를 읽을 수 없었다.
대신 HttpHeader의 Content-Length를 이용해 body를 가져올 수 있다.
HttpMessage의 Header를 파싱하자
BufferedReader에서 Header와 Body의 경계인 CRLF까지만 읽도록 한다.
public class WebServer {
//생략
private static final Map<String,String> httpHeader = new HashMap<>();
//생략
}
private static void parseHttpRequestHeader(BufferedReader br) throws IOException {
String line = null;
line = br.readLine();
String[] firstLine = line.split(" ");
httpHeader.put(firstLine[0],firstLine[1]);
while((line = br.readLine()) != null){
if("".equals(line))
break;
String[] header = line.split(" ");
httpHeader.put(header[0].replace(":",""),header[1].trim());
}
}
Map에 헤더를 공백기준으로 잘라 넣어줬다.
후에 get으로 필요한 헤더에 접근해서 사용하면 된다.
private static String parseHttpBody(BufferedReader br) throws IOException {
int contentLength = Integer.parseInt(httpHeader.get("Content-Length"));
char[] body = new char[contentLength];
br.read(body);
return new String(body);
}
Content-Length라는 키값으로 크기를 찾아 배열을 생성한다.
read()메서드를 통해 바디를 읽고 반환한다.
아래는 전체 메인 코드다.
public static void main(String[] args) throws IOException {
try{
// 소켓 생성
serverSocket = new ServerSocket();
// IP, Port, Back_Log 설정
serverSocket.bind(
new InetSocketAddress(serverSocket.getInetAddress(),DEFAULT_PORT)
,BACK_LOG
);
logger.info("WebServer Started {} port",DEFAULT_PORT);
// 연결대기
Socket client = serverSocket.accept();
logger.info("{} : success",client.getInetAddress());
InputStream inputStream = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
// httpHeader 파싱
parseHttpRequestHeader(br);
// httpBody 파싱
String body = parseHttpBody(br);
logger.info(body);
client.close();
}catch (IOException e){
logger.error(e.getMessage());
}finally {
try{
serverSocket.close();
}catch (Exception e){}
}
}
출력이 잘되는 것을 확인 할 수 있다.
마치며
다음번엔 응답을 해보자!
'Java' 카테고리의 다른 글
Java Integer Caching (0) | 2024.04.13 |
---|---|
[우아한 테크 세미나] 우아한 객체지향 - 1 (0) | 2024.04.08 |
[WAS를 만들어보자 (2)] HTTP 메세지 출력하기 (0) | 2024.03.23 |
[WAS를 만들어보자 (1)] 자바로 TCP/IP 통신하기 (0) | 2024.03.23 |
Faker를 이용한 테스트데이터 만들기 + 데이터 30만건 밀어넣기 (0) | 2023.07.16 |