-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
📄 구현 포인트
- Log 관련 라이브러리를 추가했습니다.
- main 메서드를 추가하여 서버가 돌아갈 수 있도록 했고, 기본 포트를 8080으로 설정했습니다.
- 서버 소켓을 통해 연결을 받고, 각 연결에 대해 RequestHandler 스레드를 실행합니다.
- RequestHandler 스레드가 실행될 때 연결 정보를 로그로 출력합니다.
- HTTP 요청의 헤더 값을 로그로 출력합니다.
- 모든 요청에 대해 "안녕하세요!"를 응답합니다.
✅ 간략한 코드 설명
-
프로그래밍을 하면서 요청이나 응답, 디버깅을 원활하게 하기 위하여 Log 관련 라이브러리를 추가해줍니다.
-
서버가 돌아갈 수 있도록 main 메서드를 추가해줍니다. 해당 메서드를 가진 클래스를 webServer로 칭합니다.
-
코드가 동작하면서 port 번호가 주어지지 않는다면, 기본적으로 8080 포트로 실행할 수 있도록 설정합니다.
int port;
if(args == null || args.length == 0) {
port = DEFAULT_PORT;
} else {
port = Integer.parseInt(args[0]);
}- HTTP 기반의 요청에 대해 응답하기 위한 서버로, 서버 소켓을 통해 연결을 얻습니다.
Connect을 얻으면 RequestHandler라는 새로운 스레드가 실행되어 로직을 수행합니다.
try(ServerSocket listenSocket = new ServerSocket(port)) {
Socket connection;
while((connection = listenSocket.accept()) != null) {
RequestHandler requestHandler = new RequestHandler(connection);
requestHandler.start();
};
}- RequestHandler 스레드가 실행되면 먼저 연결 정보를 log를 통해 출력하여 보여줍니다.
public void run() {
log.debug("사용자가 연결되었습니다. Connected IP : {}, Port : {}", connect.getInetAddress(), connect.getPort());- HTTP 요청의 헤더 값도 log를 통해 출력하여 보여줍니다.
try(InputStream in = connect.getInputStream();
OutputStream out = connect.getOutputStream()) {
DataOutputStream dos = new DataOutputStream(out);
byte[] body = "안녕하세요!".getBytes(StandardCharsets.UTF_8);
response200Header(dos, body.length);
responseBody(dos, body);- 모든 요청에 대하여 응답값으로 안녕하세요를 보여줄 수 있도록 합니다.
...
response200Header(dos, body.length);
responseBody(dos, body);
private void responseBody(final DataOutputStream dos, final byte[] body) {
try {
dos.write(body, 0, body.length);
dos.writeBytes("\r\n");
dos.flush();
} catch (IOException e) {
log.error(e.getMessage());
}
}
private void response200Header(final DataOutputStream dos, final int length) {
try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type : text/html; charset=utf-8\r\n");
dos.writeBytes("Content-Length" + length + "\r\n");
dos.writeBytes("\r\n");
} catch (IOException e) {
log.error(e.getMessage());
}
}