import socket
import re
import multiprocessing
class WSGIServer(object):
def __init__(self):
# 创建套接字
self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定
self.tcp_server_socket.bind(('', 7890))
# 监听套接字
self.tcp_server_socket.listen(128)
def service_client(self, new_socket):
# 接收浏览器发送过来的请求
request = new_socket.recv(1024).decode('utf8')
request_line = request.splitlines()
print("")
print(">" * 20)
print(request_line)
file_name = ""
ret = re.match(r'[^/]+(/[^ ]*)', request_line[0])
if ret:
file_name = ret.group(1)
if file_name == '/':
file_name = '/index.html'
# 返回http格式的数据给浏览器
try:
f = open('./html' + file_name, 'rb')
except:
response = 'HTTP/1.1 404 NOT FOUND\r\n'
response += '\r\n'
response += 'file not found!'
new_socket.send(response.encode('utf8'))
else:
html_content = f.read()
f.close()
response = 'HTTP/1.1 200 OK\r\n'
response += '\r\n'
new_socket.send(response.encode('utf8'))
new_socket.send(html_content)
# 关闭连接
new_socket.close()
def run(self):
while True:
# 等待新客户端的连接
new_socket, client_addr = self.tcp_server_socket.accept()
# 为这个客户端服务
p = multiprocessing.Process(target=self.service_client, args=(new_socket,))
p.start()
new_socket.close()
# 关闭套接字
self.tcp_server_socket.close()
def main():
wsgi_server = WSGIServer()
wsgi_server.run()
if __name__ == '__main__':
main()
原文地址:https://www.cnblogs.com/dhzg/p/11370945.html
时间: 2024-11-12 03:35:54