Python 实现一个简单的web服务器

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服务器 的全部内容, 来源链接: utcz.com/z/349230.html

回到顶部