8.11 常見代理
- http/HTTPS:應用層
- socket: 底層協議,抽象的
- sockets: 不關心是什么協議 ,更萬能(也是從應用層發起的)
- websocket: 雙向的,協議 (比如:聊天框)
- websockets: 工具,這個工具實現了websocket
8.11.1 websockets
應用:微信、QQ (雙向通信)
websockets 是對 http的改造
8.11.1.1 客戶端代碼
ws_client.py
# -*- coding: utf-8 -*- # @Time : 2020/11/21 16:49 # @Author : 飯盆里 # @File : ws_client.py # @Software: PyCharm # @desc : import asyncio import websockets async def hello(): uri = 'ws://127.0.0.1:8211' async with websockets.connect(uri) as websocket: name = input("you are ? ") await websocket.send(name) print(f">>{name}") greeting = await websocket.recv() print(f"<<{greeting}") asyncio.get_event_loop().run_until_complete(hello())
8.11.1.2 服務端代碼
ws_server.py
# -*- coding: utf-8 -*- # @Time : 2020/11/21 16:49 # @Author : 飯盆里 # @File : ws_server.py # @Software: PyCharm # @desc : import asyncio import websockets async def hello(websocket,path): name = await websocket.recv() print(f'<<{name}') greeting = f"hello {name}" print(f'>>{greeting}') start_server = websockets.serve(hello,'127.0.0.1',8211) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
8.11.1.3 運行
在終端先運行服務器代碼: python ws_server.py
然后在另開一個窗口運行客戶端: ws_client.py
則可以在服務器 和 客戶端 輸出中看到問候
目前遇到一個報錯如圖:尚未解決???????????????????????????????
8.11.1.4 反向代理實現websockets通訊走Charles
- 將代碼服務器的端口改為:8212
- 配置Charles反向代理,將本地發起的請求映射到服務器的端口上
- 則現在發送的請求都會經過Charles
TLS: 是對SSL的改進,SSL的標准化
8.11.2 socket的應用
8.11.2.1 socket:底層通訊機制,多層技術的應用
- socket 是將TCP、UDP等抽象的東西進行了實現
- HTTPS 是對socket的封裝 ,HTTPS里面包含了socket、SSL等
8.11.2.2 socket的server端代碼
import socket #創建socket對象 s = socket.socket() #綁定端口 s.bind(('127.0.0.1',12345)) #等待客戶端連接 s.listen(5) while True: #建立客戶端連接 c,addr = s.accept() print("連接地址",addr) c.send('你好'.encode()) c.close()
8.11.2.3 socket的client端代碼
import socket s =socket.socket() s.connect(("127.0.0.1",12345)) print('hello') print(s.recv(1024).decode()) s.close()
8.11.2.4 連接
- 服務端:
- 客戶端:
- 不能用Charles抓包,可以用tcpdump試試
8.11.3 區別
- websocket:應用層的一個協議
- socket :抽象接口,底層
- socks代理:一種技術