MyFrame work!

박진은·2023년 5월 21일
0

시작하는 이유

  • spring frame work 으로 개발을 진행하다보니 너무 추상화 되어 있는 부분들이 가득하다. 이게 문제가 어떤 방식으로 spring boot 가 작동하는지 아직도 전혀 모르겠는 이유가 존재했다 따라서 이를 직접 구현하면서 차근차근 원리를 알아 보고 open soucce 라이브러리를 직접 구현할 수 있는 개발자가 되기 위해서 시작한다.

  • 박재성님이 쓰신 책인 자바 웹프로그래밍 next 에서 제공하는 코드를 기반으로 주어진 여구사항을 충족시키면서 천천히 해보려고 한다.

  • 근데 main method 부터 이해가 가질 않아서 모르는 부분을 하나도 남기지 않고 기록하려고 한다.

public class WebServer {
    private static final Logger log = LoggerFactory.getLogger(WebServer.class);
    private static final int DEFAULT_PORT = 8080;

    public static void main(String args[]) throws Exception {
        int port = 0;
        if (args == null || args.length == 0) {
            port = DEFAULT_PORT;
        } else {
            port = Integer.parseInt(args[0]);
        }

        // 서버소켓을 생성한다. 웹서버는 기본적으로 8080번 포트를 사용한다.

        try (ServerSocket listenSocket = new ServerSocket(port)) {
            log.info("Web Application Server started {} port.", port);

            // 클라이언트가 연결될때까지 대기한다.
            Socket connection;
            while ((connection = listenSocket.accept()) != null) {
                RequestHandler requestHandler = new RequestHandler(connection);
                requestHandler.start();
            }
        }
    }
}
  • 첫 번째 구문에서 실행당시 주어진 args 로 port 를 설정하는 구문이 나온다. 실행당시 주어진 port 가 없다면 8080을 디폴트로 가진다.

  • 이후 try catch 구문에서는 클라이언트의 요청을 기다리는 부분이다. try 구문을 사용하려면 사용하는 해당 클래스가 implements java.io.Closeable 를 구현하고 있어야한다.

try (ServerSocket listenSocket = new ServerSocket(port)) {
            log.info("Web Application Server started {} port.", port);

            // 클라이언트가 연결될때까지 대기한다.
            Socket connection;
            while ((connection = listenSocket.accept()) != null) {
                RequestHandler requestHandler = new RequestHandler(connection);
                requestHandler.start();
            }
        }

사실 나는 이부분 부터 어려워서 천천히 알아보았다.

서버

ServerSocket This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.
The actual work of the server socket is performed by an instance of the SocketImpl class.
The ServerSocket class defines convenience methods to set and get several socket options. This class also defines the setOption and getOption methods to set and query socket options. A ServerSocket supports the following options:
See Also:
SocketImpl, ServerSocketChannel

최대한 간단하게 요악하자면 server socket 을 구현한 구현체로 네트워크를 통한 요청을 기다리고 연산을 수행해 요청자에게 요청을 보내는 것을 구현한 것이다. 위의 코트에서는 port 를 명시해서 서버 소켓을 생성했다. 가장 중요한 점은 서버의 소켓이라는 점이다.

클라이언트

Socket This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.
The actual work of the socket is performed by an instance of the SocketImpl class.

The Socket class defines convenience methods to set and get several socket options. This class also defines the setOption and getOption methods to set and query socket options.

Socket 은 다른 클라이언트의 소켓을 구현한것으로 실제 동작은 SocketImpl.class 에 의해서 이루어진다. 이점은 ServerSocket과 동일하다.

SocketImpl

어디까지 파야하는지 잠시 혼돈이 왔는데 딱 여기까지 파야할것 같다.


    /**
     * The file descriptor object for this socket.
     */
    protected FileDescriptor fd;

    /**
     * The IP address of the remote end of this socket.
     */
    protected InetAddress address;

    /**
     * The port number on the remote host to which this socket is connected.
     */
    protected int port;

    /**
     * The local port number to which this socket is connected.
     */
    protected int localport;

위의 필드를 보면 각각

  • 파일 디스크립터: (운영체제에서 배운것 여기서 서먹을 줄이야) 파일에 대한 고유 정보를 담고 있다.
  • IP
  • port 소켓이 연결되어있는 (한쪽 포트 예를 들면 remote host) 한국어로 뭐라고 할까 원격 주인?? 하여간 반대편 포트넘버이다.
  • localport 소켓이 연결되어있는 우리쪽 포트넘버이다.

while ((connection = listenSocket.accept()) != null)

이 루프는 클라이언트의 요청이 수신 대기 큐에 들어오면 블록되어있다가 실행된다. 따라서 운영체제 단에서의 wating 에서 run 으로 동작한다.
이 후 클라이언트 소켓이 반환되면 구현한 RequestHandler에 전달되는데 이후 RequestHandler 스레드를 생성하여 실행하는 동작을 수행한다.

profile
코딩

0개의 댓글