0%

httpServer

http协议是TCP协议的典型应用,是浏览器与服务器交流的主要方式,服务器会监听80端口,等待客户端连接

本blog在创建socket客户端和服务端的基础上,采用python socket和多线程构造一个简易的tinyHTTP,可以通过多线程并发支持多客户端请求,同时对客户端进行响应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 由socket服务端改造为httpServer,
import socket
import threading
import os

#处理http客户端请求
def handle_http_client(c, addr):
print(addr, "connected.")
WEBROOT = os.path.dirname(__file__)
print("WEBROOT",WEBROOT)
with c:
request = c.recv(1024)

# Parse HTTP headers
headers = request.split(b"\r\n")
print(headers)
file = headers[0].split()[1].decode()
print("file",file)
# Load file content
if file == "/":
file = "index.html"

try:
with open(WEBROOT + file, "rb") as f:
content = f.read()
response = b"HTTP/1.0 200 OK\r\n\r\n" + content
except FileNotFoundError:
response = b"HTTP/1.0 404 NOT FOUND\r\n\r\nFile not found!"
# Send HTTP response
c.sendall(response)

#处理socket客户端请求
def handle_client(c,addr):
print(addr,"connected.")
while True:
data = c.recv(1024)
if not data:
break
c.sendall(data)

with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
s.bind(("0.0.0.0",1234))
s.listen()

while True:
c, addr = s.accept()
t = threading.Thread(target=handle_http_client, args=(c,addr))
t.start()
1
2
3
4
5
6
7
8
# socket客户端 这里未实现http客户端(直接用浏览器代替)
import socket

with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
s.connect(("127.0.0.1",1234))
s.sendall(b"Hello,Xiaoming!")
data = s.recv(1024)
print("Received:",repr(data))