Python 实现一个简单的web服务器
程序员文章站
2023-02-19 17:28:28
import reimport socketdef service_cilent(new_socket): request = new_socket.recv(1024).decode("utf-8...
import re import socket def service_cilent(new_socket): request = new_socket.recv(1024).decode("utf-8") # python splitlines() 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 false,不包含换行符,如果为 true,则保留换行符。 request_lines = request.splitlines() print(request_lines) file_name = "" ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0]) if ret: file_name = ret.group(1) if file_name == "/": file_name = "index.html" try: f = open(file_name, "rb") except: response = "http/1.1 404 not found\r\n\r\n" response += "------file not found-----" new_socket.send(response.encode("utf-8")) else: # 打开文件成功就读文件 然后关闭文件指针 html_content = f.read() f.close() # 准备发送给浏览器的数据---header response = "http/1.1 200 ok\r\n\r\n" # 将response header发送给浏览器 new_socket.send(response.encode("utf-8")) # 将response body发送给浏览器 new_socket.send(html_content) # 关闭套接字 new_socket.close() def main(): # 创建套接字 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.bind(("", 7089)) # 监听套接字 tcp_server_socket.listen(128) while true: new_socket, cilent_addr = tcp_server_socket.accept() service_cilent(new_socket) # 关闭监听套接字 tcp_server_socket.close() if __name__ == '__main__': main()
以上就是python 实现一个简单的web服务器的详细内容,更多关于python 实现web服务器的资料请关注其它相关文章!