最近半个月学了python web方面的有关知识,web开发通常是从某一些框架开始学习 比如Django,flask。但是我个人觉得只有自己实现一遍才能更好的理解,印象也会更加深刻。希望个人的经验能对你有一些帮助
(1) 编写一个固定页面的web服务器
编写web服务器之前,你需要了解一下知识:
socket,http协议,tcp/ip协议,操作系统进程等方面的知识
一次HTTP请求所经历的步骤如下:
(1)客户端(通常为浏览器)发送请求
(2)服务器创建socket
(3)socket 绑定服务器
(4)socket 监听
(5)socket 接受客户端请求
(6)多进程处理客户端请求
(7)中断请求
代码
import socket
from multiprocessing import Process
def handle_client(client_socket):
request_data = client_socket.recv(1024)
print("request_data:" , request_data)
response_start_line = "HTTP/1.1 200 OK\r\n"
response_heads = "Server:Myserver\r\n"
response_body = "This is a easy static web server"
response = response_start_line + response_heads + "\r\n" + response_body
print("response_data:", response)
client_socket.send(bytes(response, "utf-8"))
client_socket.close()
if __name__ == "__main__":
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
server_socket.bind(("", 8000))
server_socket.listen(128)
while True:
client_socket,client_address = server_socket.accept()
print("[%s %s]用户连接上了" % client_address)
client_socket_process = Process(target=handle_client, args=(client_socket,))
client_socket_process.start()
client_socket.close()