HTTPサーバーとHTTPクライアントを作ってみよう
ソケット | socketを使ってTCP上で動くHTTPサーバーとクライアントをpythonで作る
https://github.com/yuiseki/study_http
サーバー
code:http-server.py
# -*- coding : UTF-8 -*-
import socket
import textwrap
tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server.bind(("127.0.0.1", 8080))
tcp_server.listen(5)
try:
while True:
res, address = tcp_server.accept()
print("* Connected!! Source : {}".format(address))
reqraw = res.recv(1024)
if len(reqraw) == 0:
continue
req = reqraw.decode('utf-8')
firstline = req.split('\r\n')0
method = firstline.split(' ')0
path = firstline.split(' ')1
print("* Path : {}".format(path))
print("* Method : {}".format(method))
resstr = """
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 11
hello world
"""
resstr = textwrap.dedent(resstr).strip()
print(resstr)
res.send(resstr.encode('utf-8'))
res.close()
print("-----")
except KeyboardInterrupt:
pass 
python3 http-server.py
http://localhost:8080/
code:http-client.py
code:post.txt
POST /test HTTP/1.1
Host: 127.0.0.1:8080
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
field1=value1&field2=value2
params[:field1]