#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()