溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用python 寫一個(gè)靜態(tài)服務(wù)(實(shí)戰(zhàn))

發(fā)布時(shí)間:2020-10-25 03:40:01 來(lái)源:腳本之家 閱讀:178 作者:陶瑞同學(xué) 欄目:開發(fā)技術(shù)

師父布置的任務(wù),讓我寫一個(gè)服務(wù)練練手,搞清楚socket的原理和過程后跑了一個(gè)小demo,很有成就感,代碼內(nèi)容也比較清晰易懂,很有教育啟發(fā)意義。

代碼

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

HTML_ROOT_DIR = ""


def handle_client(client_socket):
  """處理客戶端請(qǐng)求"""
  # 獲取客戶端請(qǐng)求數(shù)據(jù)
  request_data = client_socket.recv(1024)
  print("request data:", request_data)

  # 構(gòu)造響應(yīng)數(shù)據(jù)
  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)

  # 向客戶端返回響應(yīng)數(shù)據(jù)
  client_socket.send(bytes(response, "utf-8"))

  # 關(guān)閉客戶端連接
  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()

運(yùn)行后在瀏覽器輸入:127.0.0.1:8000

http頁(yè)面顯示如下:

使用python 寫一個(gè)靜態(tài)服務(wù)(實(shí)戰(zhàn))

控制臺(tái)輸出:

[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 寫一個(gè)靜態(tài)服務(wù)(實(shí)戰(zhàn))就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI