python实现HTTP服务器

mac2025-09-29  16

利用Python编写http服务器: 目的:服务器可以被任意电脑的任意浏览器访问: 程序需导入两个模块:re模块,socket模块

主main()函数中:

1.创建TCP套接字Socket.

http_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

2.绑定服务器的IP和端口

http_socket.bind(("IP",port))

3.进行套接字的监听

http_socket.listen(128)

4.``accept返回新的套接字和来访问的地址

new_socket, host_address = http_socket.accept()
再创建函数recv_send():*

在这个函数中,主要完成对浏览器进行数据接收和回复,则主要使用新套接字,new_socket 接收并解码:recv_data = new_socket.recv(2096).decode("utf-8") 接收的数据要进行正则匹配,提取有用的数据,之后才能有效的进行浏览器的回复。浏览器发送的数据主要为“GET /** HTTP/1.1”,而正则表达式就是为了获取GET和HTTP/1.1之间的内容。

ret = re.match(r"[^/]+(/[^ ]*)", recv_lines[0])

这个正则匹配需要对接收浏览器发来的数据阅读。 例如,浏览器发来的数据为’GET /01day/index.html HTTP/1.1’,从GET开始,匹配是否有“/”,若没有,继续查找。若有则从“/”开始,直到第一个空格结束,则输出的数据为:“/01day/index.html” 得到浏览器需要的网页,则要在相应的位置找到这个文件,并将其发送给浏览器if ret: file_name = ret.group(1),f = open(".\\" + file_name, "rb"),file_data = f.read() f.close() 发送:new_socket.send(file_data) 打开文件是十分的危险,要非常小心,所以在打开文件时,要进行异常捕获`.

try: f = open(".\\" + file_name, "rb") except: response = "HTTP/1.1 404 NOT FOUND\r\n" response += "\r\n" response += "<h1>NO REPLAY</h1>" new_socket.send(response.encode("utf-8")) else: file_data = f.read() f.close() response = "HTTP/1.1 200 OK\r\n" response += "\r\n" """将Header发送""" new_socket.send(response.encode("utf-8")) """将Body发送""" new_socket.send(file_data)

最后将套接字关闭:new_socket.close() http_socket.close()

最新回复(0)