본문 바로가기

etc

[HTTP] HTTP Server 빌드하기 / 파이썬 사용

해당 포스트는 Let's Build A Web Server. Part 1. - by.Ruslan 을 읽고 정리한 글입니다.

I believe to become a better developer you MUST get a better understanding of the underlying software systems you use on a daily basis and that includes programming languages, compilers and interpreters, databases and operating systems, web servers and web frameworks. And, to get a better and deeper understanding of those systems you MUST re-build them from scratch, brick by brick, wall by wall.

Web Server란?

web server은 client가 request를 보내기를 기다렸다가 requeset를 받으면 reponse를 만들어서 client에게 보내는 역할을 한다.

이때 client와 server 사이의 communication은 HTTP protocol을 이용하는 것이다.

 

간단한 web server 구현

# Python3.7+
# webserver1.py
import socket

HOST, PORT = '', 8888

# socket 객체 생성: 주소체계는 IPv4, socket type은 tcp 사용
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1) # 서버 listen(클라이언트의 접속 허용)
print(f'Serving HTTP on port {PORT} ...')
while True:
    client_connection, client_address = listen_socket.accept()
    request_data = client_connection.recv(1024)
    print(request_data.decode('utf-8'))

    http_response = b"""\
HTTP/1.1 200 ok

Hello, World!
"""
    client_connection.sendall(http_response)
    client_connection.close()
$ python webserver1.py

http://localhost:8888 접속

 

TCP connection

client(여기선 browser)는 HTTP request를 보내기 전에 web server와 TCP connection을 맺어야 한다.

그래야 HTTP request를 TCP connection 위에서 server로 보내고 server가 HTTP reponse를 보내주기를 기다릴 수 있다.

 

client와 server은 TCPconnection을 맺기 위해 sockets를 사용한다.

이를 자세히 알아보기 위해 브라우저 대신 cli에서 telnet을 이용해보자

그전에, 제어판->프로그램 기능 켜기/끄기 -> Telnet client 체크!

$ telnet localhost 8888

이 시점에 localhost에서 실행되고 있는 server와 TCP connection을 맺은 것이다.

 

같은 telnet session에서 GET /hello HTTP/1.1을 입력하면 Hello, world! 메세지를 볼 수 있다.