Python網絡編程—TCP套接字之HTTP傳輸


HTTP協議 (超文本傳輸協議)

1.用途 : 網頁獲取,數據的傳輸

2.特點:

  • 應用層協議,傳輸層使用tcp傳輸
  • 簡單,靈活,很多語言都有HTTP專門接口
  • 無狀態,協議不記錄傳輸內容
  • http1.1 支持持久連接,豐富了請求類型

3.網頁請求過程

  1. 客戶端(瀏覽器)通過tcp傳輸,發送http請求給服務端
  2. 服務端接收到http請求后進行解析
  3. 服務端處理請求內容,組織響應內容
  4. 服務端將響應內容以http響應格式發送給瀏覽器
  5. 瀏覽器接收到響應內容,解析展示

HTTP請求(request)

1.請求行 : 具體的請求類別和請求內容

  • GET / HTTP/1.1
  • 請求類別 請求內容 協議版本

請求類別:每個請求類別表示要做不同的事情

  • GET : 獲取網絡資源
  • POST :提交一定的信息,得到反饋
  • HEAD : 只獲取網絡資源的響應頭
  • PUT : 更新服務器資源
  • DELETE : 刪除服務器資源
  • CONNECT
  • TRACE : 測試
  • OPTIONS : 獲取服務器性能信息

2.請求頭:對請求的進一步解釋和描述

  • Accept-Encoding: gzip

3.空行

4.請求體: 請求參數或者提交內容

 1 from socket import *
 2 
 3 s = socket()
 4 s.bind(('0.0.0.0',8001))
 5 s.listen(3)
 6 c,addr = s.accept()
 7 print("Connect from",addr)
 8 data = c.recv(4096)
 9 print(data)
10 
11 data = """HTTP/1.1 200 OK
12 Content-Type:text/html
13 
14 <h1>Hello world</h1>
15 """
16 c.send(data.encode())
17 
18 c.close()
19 s.close()
http 請求響應示例

http響應(response)

響應格式:響應行,響應頭,空行,響應體

響應行 : 反饋基本的響應情況

  • HTTP/1.1 200 OK
  • 版本信息 響應碼 附加信息

響應碼 :

  • 1xx 提示信息,表示請求被接收
  • 2xx 響應成功
  • 3xx 響應需要進一步操作,重定向
  • 4xx 客戶端錯誤
  • 5xx 服務器錯誤

響應頭:對響應內容的描述

  • Content-Type: text/html

響應體:響應的主體內容信息

 1 from socket import *
 2 
 3 # 處理客戶端請求
 4 def handle(connfd):
 5   request = connfd.recv(4096) # 接收請求
 6   # 防止客戶端斷開request為空
 7   if not request:
 8     return
 9   request_line = request.splitlines()[0]
10   info = request_line.decode().split(' ')[1]
11   if info == '/':
12     with open('index.html') as f:
13       response = "HTTP/1.1 200 OK\r\n"
14       response += "Content-Type:text/html\r\n"
15       response += '\r\n'
16       response += f.read()
17   else:
18     response = "HTTP/1.1 404 Not Found\r\n"
19     response += "Content-Type:text/html\r\n"
20     response += '\r\n'
21     response += "<h1>Sorry...</h1>"
22   # 發送給瀏覽器
23   connfd.send(response.encode())
24 
25 
26 # 搭建tcp網絡
27 sockfd = socket()
28 sockfd.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
29 sockfd.bind(('0.0.0.0',8000))
30 sockfd.listen(3)
31 while True:
32   connfd,addr = sockfd.accept()
33   handle(connfd)  # 處理客戶端請求
http 發送網頁給瀏覽器

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM