from multiprocessing import Process
import socket
import re
HTML_ROOT_DIR = './html'
def handleClient(client):
#读取客户端请求数据
request_data = client.recv(1024)
request_data_list = request_data.splitlines()
httpRequestMethodLine = request_data_list[0]
httpRequestMethodLine = httpRequestMethodLine.decode('utf-8')
try:
ret = re.match(r'\w*\s+(/[^\s]*)\s+',httpRequestMethodLine)
except AttributeError:
print('not match!')
else:
sub_dir = ret.group(1)
if sub_dir == '/':
sub_dir = '/index.html'
path = HTML_ROOT_DIR + sub_dir
response_start_line = 'HTTP/1.1 200 OK\r\n'
response_headers = 'Server:My server\r\n'
try:
file = open(path)
except FileNotFoundError:
response_body = '\r\n' + '找不到该资源'
response = response_start_line + response_headers + response_body
else:
html = file.read()
response_body = '\r\n' + str(html)
response = response_start_line + response_headers + response_body
file.close()
finally:
client.send(bytes(response, 'utf-8'))
client.close()
def main():
# 创建服务器
webServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#设置socket选项,地址以及端口可复用
webServer.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
webServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
# 判定端口号
webServer.bind(('127.0.0.1', 9000))
# 开始监听
webServer.listen()
while True:
# 接收客户端
client, addressInfo = webServer.accept()
# 创建进程,单独执行客户端任务
client_process = Process(target=handleClient, args=(client,))
client_process.start()
client.close()
if __name__ == '__main__':
main()
Python Web服务器案例
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Python实现简单的Web服务器 https://www.shiyanlou.com/courses/552/l...