#coding=utf-8
import socket
import re
import threading
import multiprocessing
import gevent
from gevent import monkey
monkey.patch_all() # 遇到阻塞自动切换协程,程序启动时执行monkey.patch_all()解决
def service_client(new_socket, request):
'''为这个客户端返回数据'''
# 1. 接收浏览器发过来的请求,即http请求
# GET / HTTP/1.1
# ...
# request = new_socket.recv(1024).decode('UTF-8') # 解码
#print('>>>'*40)
#print(request)
request_lines = request.splitlines() # 转换成列表
print('')
print('>'*30)
print(request_lines)
# GET /index.html HTTP/1.1
# get post put del
ret = re.match(r'[^/]+(/[^ ]*)', request_lines[0])
if ret:
file_name = ret.group(1)
print('*'*50, file_name)
if file_name == '/':
file_name = '/index.html'
# 2. 返回http格式的数据给浏览器
try:
f = open('./html' + file_name, 'rb')
except:
response = 'HTTP/1.1 404 NOT FOUND\r\n'
response += '\r\n'
response += '----file not find----'
new_socket.send(response.encode('utf-8'))
else:
html_content = f.read()
f.close()
# 2.1 准备发送给浏览器的数据 -- header,body
response_body = html_content
response_header = 'HTTP/1.1 200 OK\r\n'
response_header += 'Content-Length:%d\r\n' % len(response_body)
response_header += '\r\n' # 空行
response = response_header.encode('utf-8') + response_body
# 2.2 将response header + body 发送给浏览器
new_socket.send(response)
# 关闭套接字
# new_socket.close()
def main():
'''整体控制'''
# 1. 创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcp_server_socket.setblocking(False) # 设置套接字为非堵塞
# 2. 绑定本地信息
tcp_server_socket.bind(('', 7890))
# 3. 开启监听
tcp_server_socket.listen(128)
tcp_server_socket.setblocking(False) # 将套接字变为非堵塞
client_socket_list = list()
while True:
# 4. 等待新客户端的连接
try:
new_socket, client_addr = tcp_server_socket.accept()
except Exception as ret:
pass
else:
new_socket.setblocking(False) # 新套接字变为非堵塞
client_socket_list.append(new_socket)
for new_socket in client_socket_list:
try:
recv_data = new_socket.recv(1024).decode('utf-8')
except Exception as ret:
pass
else:
if recv_data:
service_client(new_socket, recv_data)
else:
new_socket.close()
client_socket_list.remove(new_socket)
# 关闭监听套接字
tcp_server_socket.close()
if __name__ == '__main__':
main()