Create primitive fork HTTP server
This commit is contained in:
commit
d54b74e65f
2 changed files with 56 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
*.log
|
||||
*.swp
|
54
__main__.py
Executable file
54
__main__.py
Executable file
|
@ -0,0 +1,54 @@
|
|||
#!/usr/bin/python3.12
|
||||
|
||||
import os
|
||||
import socket
|
||||
import logging
|
||||
|
||||
|
||||
MAX_REQLINE = 64 * 1024
|
||||
|
||||
def service_connections(conn, addr):
|
||||
recv_file = conn.makefile("rb")
|
||||
|
||||
logging.debug("START RECV")
|
||||
raw = recv_file.readline(MAX_REQLINE + 1)
|
||||
logging.debug("END RDLINE")
|
||||
if len(raw) > MAX_REQLINE:
|
||||
logging.debug("Request line is too long")
|
||||
return
|
||||
|
||||
req_line = raw.decode().rstrip("\r\n")
|
||||
|
||||
words = req_line.split(" ")
|
||||
|
||||
if len(words) != 3:
|
||||
logging.debug("Request head too long")
|
||||
return
|
||||
|
||||
if words[0] == "GET":
|
||||
logging.debug("SEND")
|
||||
conn.send(b"HTTP/1.1 200 OK\r\nServer: cnserv\r\n\r\nNone")
|
||||
logging.debug("SENDEND")
|
||||
conn.close()
|
||||
logging.debug("CONNEND")
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(filename="main.log", filemode="w", encoding="UTF-8",
|
||||
level=logging.DEBUG)
|
||||
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as main_server_socket:
|
||||
main_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
|
||||
main_server_socket.bind(("0.0.0.0", 8080))
|
||||
main_server_socket.listen()
|
||||
|
||||
while True:
|
||||
conn, addr = main_server_socket.accept()
|
||||
conn.settimeout(1)
|
||||
logging.info("Accept connection from %s", addr[0])
|
||||
|
||||
pid = os.fork()
|
||||
|
||||
if pid == 0:
|
||||
service_connections(conn, addr)
|
Loading…
Reference in a new issue