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服務器的詳細內容,更多關於python 實現web服務器的資料請關註WalkonNet其它相關文章!

推薦閱讀: