简单的面向对象-web服务器
Posted dhzg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的面向对象-web服务器相关的知识,希望对你有一定的参考价值。
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()
以上是关于简单的面向对象-web服务器的主要内容,如果未能解决你的问题,请参考以下文章