立即學習:https://edu.csdn.net/course/play/24458/296240?utm_source=blogtoedu
?????? 粘包現象:服務器接收到客戶端的命令后,進行執行得到結果后,再發送回給客戶端,在這個過程中如果服務器返回的結果的字節數會大于客戶端所接收最大字節數(此處以1024為客戶端接收的最大字節數),則大于1024字節的殘余結果會堆積在服務器發送返回客戶端的管道中,這個現象叫做殘余數據。等下一次再執行客戶端命令返回命令結果給客戶端時,會先把管道中的殘余數據發送返回給客戶端,這時候就會出現客戶端接收的結果并不是自己發送命令所希望得到的結果,因為所接收的結果含有上一次執行時的殘余數據甚至只有殘余數據,即多次命令(也成為多個包)的結果摻雜在了一起,這種現象成為粘包現象。例子如下:
'''先運行服務器端,再在客戶端上一次輸入dir、tasklist、dir命令,觀察服務器端執行命令的結果的字節數長度,以及觀察客戶端接收到的結果,尤其是兩次運行dir命令的結果
'''客戶端的結果:'''
E:\python3\venv2\venv\Scripts\python.exe C:/Users/jinlin/Desktop/python_further_study/socket編程/簡單的套接字通訊加循環/客戶端.py
請輸入命名:dir
服務器返回來的數據: 驅動器 C 中的卷是 本地磁盤卷的序列號是 B476-3C7CC:\Users\jinlin\Desktop\python_further_study\socket編程\模擬ssh遠程操作命令 的目錄2020/03/09 10:57 <DIR> .
2020/03/09 10:57 <DIR> ..
2020/03/07 13:35 0 __init__.py
2020/03/07 10:02 895 客戶端_.py
2020/03/09 10:57 1,112 服務器端_.py3 個文件 2,007 字節2 個目錄 124,751,876,096 可用字節**************************************************
請輸入命名:tasklist
服務器返回來的數據:
映像名稱 PID 會話名 會話# 內存使用
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 4 K
System 4 Services 0 588 K
smss.exe 324 Services 0 804 K
csrss.exe 524 Services 0 9,064 K
csrss.exe 620 Console 1 32,996 K
wininit.exe 628 Services 0 4,144 K
winlogon.exe 656 Console 1 6,692 K
services.exe 724 Services 0 8,568 K
lsass.exe 732 Services 0 11,756 K
svchost.exe 804 Services 0 11,556 K
svchost.exe 844 Services 0 9,336 K
dwm.exe
**************************************************
請輸入命名:dir
服務器返回來的數據: 948 Console 1 24,656 K
nvvsvc.exe 956 Services 0 2,648 K
nvxdsync.exe 1000 Console 1 7,264 K
nvvsvc.exe 1008 Console 1 1,684 K
svchost.exe 276 Services 0 31,996 K
svchost.exe 392 Services 0 48,924 K
svchost.exe 412 Services 0 25,584 K
svchost.exe 736 Services 0 49,284 K
RtkAudioService64.exe 1056 Services 0 4 K
RAVBg64.exe 1076 Console 1 1,596 K
RAVBg64.exe 1084 Console 1 1,432 K
ZhuDongFangYu.exe 1128 Services 0 4,528 K
svchost.exe 1280 Services 0 17,032 K
spoolsv.exe
**************************************************'''服務器端的結果:
'''
464
**************************************************
9674
**************************************************
464
**************************************************'''
?????? 由上可知,dir命令返回的結果字節數是496,由tasklist運行的結果字節數為9766個,因此兩次的dir命令執行的結果不一樣,因為第二次dir命令的結果與tasklist命令的結果混在了一起,產生了粘包現象。
?
簡單的粘包原因如下圖: