当前位置:首页 >> 脚本专栏

使用python 写一个静态服务(实战)

师父布置的任务,让我写一个服务练练手,搞清楚socket的原理和过程后跑了一个小demo,很有成就感,代码内容也比较清晰易懂,很有教育启发意义。

代码

# coding:utf-8
import socket
from multiprocessing import Process

HTML_ROOT_DIR = ""


def handle_client(client_socket):
  """处理客户端请求"""
  # 获取客户端请求数据
  request_data = client_socket.recv(1024)
  print("request data:", request_data)

  # 构造响应数据
  response_start_line = "HTTP/1.1 200 OK\r\n"
  response_headers = "Server: My server\r\n"
  response_body = "hello itcast"
  response = response_start_line + response_headers + "\r\n" + response_body
  print("response data:", response)

  # 向客户端返回响应数据
  client_socket.send(bytes(response, "utf-8"))

  # 关闭客户端连接
  client_socket.close()


if __name__=="__main__":
  server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  server_socket.bind(("", 8000))
  server_socket.listen(120)

  while True:
    client_socket, client_address = server_socket.accept()
    # print("[%s, %s]用户连接上了"%client_addrest[0],client_address[1])
    print("[%s, %s]用户连接上了" % client_address)
    handle_client_process = Process(target=handle_client, args=(client_socket,))
    handle_client_process.start()
    client_socket.close()

运行后在浏览器输入:127.0.0.1:8000

http页面显示如下:

使用python 写一个静态服务(实战)

控制台输出:

[127.0.0.1, 50066]用户连接上了
request data: b'GET / HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nUpgrade-Insecure-Requests: 1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5\r\nAccept-Language: zh-cn\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n\r\n'
response data: HTTP/1.1 200 OK
Server: My server

hello itcast
[127.0.0.1, 50067]用户连接上了
request data: b'GET /favicon.ico HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nConnection: keep-alive\r\nAccept: */*\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5\r\nAccept-Language: zh-cn\r\nReferer: http://127.0.0.1:8000/\r\nAccept-Encoding: gzip, deflate\r\n\r\n'
response data: HTTP/1.1 200 OK
Server: My server

hello itcast

以上这篇使用python 写一个静态服务(实战)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。