본문 바로가기
웹서버/톰캣

톰캣 - 1

by 디찌s 2023. 8. 16.
728x90
반응형

socket class ,... server socket class..

 

java에서 socket 클래스는 클라이언트 소켓을 표현한다.

 

HTTP,FTP 서버를 구성하려면 Server socket을 구현해야한다.

 

client는 언제 연결을 할지 모르기때문에 http server 는 항상 대기하고 있어야한다.

 

server socket 과 일반 socket은 다르다!

 

Server socket

서버 소켓은 연결을 다루기위해 클라이언트가 연결되자마자 socket instance를 생성한다.

 

 

서버 소켓의 백로그란?

서버 소켓이 수신 요청을 거부하기 전에 수신 연결 요청의 최대 대기열 길이입니다.

 

keep-alive 에 존재이유?

http 통신에서 일반적으로 클라이언트와 서버가 소통을 할때 , 소켓을 연결 및 끊기를 한다. 예를들어

 

클라이언트에서 3개의 리소스를 서버에 요청할때 3개의 소켓(커넥션)이 발생한다. 이렇게 되다보니 소켓을 생성 및 끊기에 대한 리소스를

 

많이 사용하게 되고 불필요하게 소모되는 자원을 줄이기 위해 keep alive를 통해 일정시간동안 소켓 연결을 유지하여 자원낭비를 줄인다.

 

 

아래 코드는 response 코드이다..

 

브라우저가 request 메세지를 보내면(localhost:8080/index.html) ,  Webroot 즉 , index.html이 존재하는 경로에서 해당 파일을 읽고 outputstream을 통해 브라우저에 데이터를 전송 역할을 하는 메소드이다.

 byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        try {
            File file = new File(HttpServer.WEB_ROOT, request.getUri());
            if (file.exists()) {
                // 响应头
                output.write("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n".getBytes());
                fis = new FileInputStream(file);
                int ch = fis.read(bytes, 0, BUFFER_SIZE);
                while (ch != -1) {
                    output.write(bytes, 0, ch);
                    ch = fis.read(bytes, 0, BUFFER_SIZE);
                }
                output.flush();
            } else {
                // file not found
                String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 23\r\n" +
                        "\r\n" +
                        "<h1>File Not Found</h1>";
                output.write(errorMessage.getBytes());
            }
        } catch (Exception e) {
            // thrown if cannot instantiate a File object
            System.out.println(e.toString());
        } finally {
            if (fis != null)
                fis.close();
        }
728x90
반응형

댓글