日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python实现http协议_python使用socket实现TCP支持HTTP协议的静态网页服务器

發布時間:2025/3/19 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python实现http协议_python使用socket实现TCP支持HTTP协议的静态网页服务器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

直接上代碼:

from multiprocessing import Process

import re

import socket

HTML_ROOT_DIR = "./html"

class HTTPServer(object):

"""服務器"""

def __init__(self):

self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# self.server_socket.bind("", port)

def start(self):

"""開啟服務器"""

self.server_socket.listen(128)

while True:

client_socket, client_addr = self.server_socket.accept()

print("[%s, %s]用戶連接上了..." % client_addr)

handle_client_process = Process(target=self.handle_client, args=(client_socket,))

handle_client_process.start()

client_socket.close()

def handle_client(self, client_socket):

"""處理客戶端請求"""

request_data = client_socket.recv(1024)

print("request_data: ", request_data)

request_lines = request_data.splitlines()

for line in request_lines:

print(line)

request_start_line = request_lines[0]

file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)

if "/" == file_name:

file_name = "/index.html"

try:

file = open(HTML_ROOT_DIR + file_name, "rb")

except IOError:

response_start_line = "HTTP/1.1 404 Not Fount\r\n"

response_head_line = "server: My server\r\n"

response_body = "The File is not Found!"

else:

file_data = file.read()

file.close()

response_start_line = "HTTP/1.1 200 OK\r\n"

response_head_line = "Server: My server\r\n"

response_body = file_data.decode("utf-8")

finally:

response = response_start_line + response_head_line + "\r\n" + response_body

print("response data: ", response)

client_socket.send(bytes(response, "utf-8"))

client_socket.close()

def bind(self, port):

self.server_socket.bind(("", port))

def main():

http_server = HTTPServer()

http_server.bind(8000)

http_server.start()

if __name__ == "__main__":

main()

總結

以上是生活随笔為你收集整理的python实现http协议_python使用socket实现TCP支持HTTP协议的静态网页服务器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。