python網路程式設計基礎之socket粘包現象
阿新 • • 發佈:2018-11-23
粘包現象兩種
登陸
#服務端
import json import socket server=socket.socket()#建立socket物件 ip_port=('127.0.0.1',8001)#獲取本機迴環地址和通訊埠號 server.bind(ip_port)#繫結ip地址和埠號 #設定使用者名稱和密碼 username='alex' password='123' server.listen()#監聽服務埠號 conn,addr=server.accept() while 1: ''' from_client_msg接受客戶端的使用者資訊 user_info_dict=json.loads(from_client_msg)接受使用者資訊轉換成字典''' from_client_msg=conn.recv(1024).decode('utf-8') user_info_dict=json.loads(from_client_msg) print(user_info_dict) if username==user_info_dict['username'] and password ==user_info_dict['password']: #設定200是登陸成功的狀態碼 conn.send(b'200') break else: # 設定250是登陸失敗的狀態碼conn.send(b'250') conn.close() server.close()
#客戶端
import json import socket client=socket.socket() #建立socket套接字物件 ip_port=('127.0.0.1',8001)#獲取ip地址和埠號 client.connect(ip_port)#客戶端連線IP地址 while 1: #讓使用者輸入使用者名稱和密碼 uname=input("請輸入使用者名稱:").strip() pwd=input("請輸入密碼:").strip() #定義一個字典來儲存使用者登陸資訊 user_info={'username':uname,'password':pwd} ''' 因為send的資料型別必須是bytes型別,所有需要將字典轉換為bytes型別, 但是字典無法直接轉換成bytes,所以我們使用json序列化,先轉換成str ''' user_info_json=json.dumps(user_info) user_info_str=user_info_json.encode('utf-8') # 客戶端傳送資訊 client.send(user_info_str) #接收到服務端的返回資訊 from_server_data=client.recv(1024).decode('utf-8') if from_server_data=='200': print('登陸成功') break else: print('使用者名稱或密碼錯誤') client.close()
一.連續的小包,會被優化機制給合併,程式碼如下
服務端:
import socket server=socket.socket() ip_port=('127.0.0.1',8001) server.bind(ip_port) server.listen() conn,addr=server.accept() from_client_msg1=conn.recv(1024).decode('utf-8') from_client_msg2=conn.recv(1024).decode('utf-8') print('from_client_msg1>>>',from_client_msg1)
客戶端:
import socket client=socket.socket() ip_port=('127.0.0.1',8001) client.connect(ip_port) client.send(b'12') client.send(b'22')
解決方案
服務端程式碼如下
import socket import subprocess server = socket.socket() ip_port = ('127.0.0.1',8001) server.bind(ip_port) server.listen() conn,addr = server.accept() while 1: from_client_cmd = conn.recv(1024).decode('utf-8') sub_obj = subprocess.Popen( from_client_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) #subprocess物件.read 得到的結果是bytes型別的 cmd_res = sub_obj.stdout.read() data_len = len(cmd_res) data_len_str = str(data_len) print('結果長度>>>',data_len) conn.send(data_len_str.encode('utf-8')) client_stutas = conn.recv(1024).decode('utf-8') if client_stutas == 'ok': conn.send(cmd_res) else: print('客戶端長度資訊沒有收到')
客戶端程式碼如下
import json import socket client = socket.socket() ip_port = ('127.0.0.1',8001) client.connect(ip_port) while 1: client_cmd = input('請輸入系統指令>>>') client.send(client_cmd.encode('utf-8')) from_server_datalen = client.recv(1024).decode('utf-8') client.send(b'ok') from_server_result = client.recv(int(from_server_datalen)) print(from_server_result.decode('gbk'))
二.服務端一次性無法完全就收完客戶端傳送的資料,第二再次接收的時候,會接收到第一次遺留的內容
服務端
import socket import subprocess server = socket.socket() ip_port = ('127.0.0.1',8001) server.bind(ip_port) server.listen() conn,addr = server.accept() while 1: from_client_cmd = conn.recv(1024).decode('utf-8') sub_obj = subprocess.Popen( from_client_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) #subprocess物件.read 得到的結果是bytes型別的 cmd_res = sub_obj.stdout.read() print('結果長度>>>',len(cmd_res)) conn.send(cmd_res)
客戶端
import json import socket client = socket.socket() ip_port = ('127.0.0.1',8001) client.connect(ip_port) while 1: client_cmd = input('請輸入系統指令>>>') client.send(client_cmd.encode('utf-8')) from_server_result = client.recv(1024) print(from_server_result.decode('gbk'))
執行程式碼試試
三,針對資料量大的粘包現象解決方案
服務端程式碼如下
import socket import subprocess server = socket.socket() ip_port = ('127.0.0.1',8001) data_full_len = 0 #統計傳送資料的長度 server.bind(ip_port) server.listen() conn,addr = server.accept() while 1: from_client_cmd = conn.recv(1024).decode('utf-8') sub_obj = subprocess.Popen( from_client_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) #subprocess物件.read 得到的結果是bytes型別的 cmd_res = sub_obj.stdout.read() data_len = len(cmd_res) #總資料長度 data_len_str = str(data_len) print('結果長度>>>',data_len) conn.send(data_len_str.encode('utf-8')) client_stutas = conn.recv(1024).decode('utf-8') if client_stutas == 'ok': #傳送真實資料 while data_full_len < data_len: every_send_data = cmd_res[data_full_len:data_full_len + 1024] every_send_datalen = len(every_send_data) conn.send(every_send_data) data_full_len += 1024 else: print('客戶端長度資訊沒有收到')
客戶端程式碼如下
import json import socket client = socket.socket() ip_port = ('127.0.0.1',8001) client.connect(ip_port) all_recv_len = 0 all_data_byte = b'' while 1: client_cmd = input('請輸入系統指令>>>') client.send(client_cmd.encode('utf-8')) from_server_datalen = client.recv(1024).decode('utf-8') all_data_len = int(from_server_datalen) #服務端傳送的總資料長度 client.send(b'ok') while all_recv_len < all_data_len: from_server_result = client.recv(1024) every_recv_len = len(from_server_result) #每次接受的資料長度 all_recv_len += every_recv_len all_data_byte += from_server_result print(all_data_byte.decode('gbk'))
2是struct模組解決粘包現象
通過struct模組,將要傳送的真實資料的長度進行打包,打包成4個位元組,和真實資料一起一次性發送個客戶端.客戶端取出前4個位元組,通過struct解包獲得後面真實資料的長度,根據這個長度再進行資料的接受
服務端程式碼如下
import socket import subprocess import struct server = socket.socket() ip_port = ('127.0.0.1',8001) data_full_len = 0 #統計傳送資料的長度 server.bind(ip_port) server.listen() conn,addr = server.accept() while 1: from_client_cmd = conn.recv(1024).decode('utf-8') sub_obj = subprocess.Popen( from_client_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) #subprocess物件.read 得到的結果是bytes型別的 cmd_res = sub_obj.stdout.read() data_len = len(cmd_res) #總資料長度 data_len_str = str(data_len) print('結果長度>>>',data_len) #將真實資料長度打包成4個位元組的資料 struct_data_len = struct.pack('i',data_len) conn.send(struct_data_len + cmd_res)
客戶端程式碼如下
import json import socket import struct client = socket.socket() ip_port = ('127.0.0.1',8001) client.connect(ip_port) all_recv_len = 0 all_data_byte = b'' while 1: client_cmd = input('請輸入系統指令>>>') client.send(client_cmd.encode('utf-8')) #先接收4個位元組,這4個位元組是真實資料長度加工成的 recv_data_len = client.recv(4) #將4個位元組長度的資料,解包成後面真實資料的長度 real_data_len = struct.unpack('i',recv_data_len)[0] print(real_data_len) server_result = client.recv(real_data_len) print(server_result.decode('gbk'))
四獲取緩衝區的方法
import socket from socket import SOL_SOCKET,SO_REUSEADDR,SO_SNDBUF,SO_RCVBUF sk = socket.socket(type=socket.SOCK_DGRAM) # sk.setsockopt(SOL_SOCKET,SO_RCVBUF,80*1024) sk.bind(('127.0.0.1',8090)) print('>>>>', (sk.getsockopt(SOL_SOCKET, SO_SNDBUF))/1024) print('>>>>', sk.getsockopt(SOL_SOCKET, SO_RCVBUF))
五.合法性連線驗證
服務端程式碼如下
from socket import * import hmac,os secret_key=b'Jedan has a big key!' def conn_auth(conn): ''' 認證客戶端連結 :param conn: :return: ''' print('開始驗證新連結的合法性') msg=os.urandom(32)#生成一個32位元組的隨機字串 conn.sendall(msg) h=hmac.new(secret_key,msg) digest=h.digest() respone=conn.recv(len(digest)) return hmac.compare_digest(respone,digest) def data_handler(conn,bufsize=1024): if not conn_auth(conn): print('該連結不合法,關閉') conn.close() return print('連結合法,開始通訊') while True: data=conn.recv(bufsize) if not data:break conn.sendall(data.upper()) def server_handler(ip_port,bufsize,backlog=5): ''' 只處理連結 :param ip_port: :return: ''' tcp_socket_server=socket(AF_INET,SOCK_STREAM) tcp_socket_server.bind(ip_port) tcp_socket_server.listen(backlog) while True: conn,addr=tcp_socket_server.accept() print('新連線[%s:%s]' %(addr[0],addr[1])) data_handler(conn,bufsize) if __name__ == '__main__': ip_port=('127.0.0.1',9999) bufsize=1024 server_handler(ip_port,bufsize)
客戶端程式碼如下
from socket import * import hmac,os secret_key=b'Jedan has a big key!' def conn_auth(conn): ''' 驗證客戶端到伺服器的連結 :param conn: :return: ''' msg=conn.recv(32) h=hmac.new(secret_key,msg) digest=h.digest() conn.sendall(digest) def client_handler(ip_port,bufsize=1024): tcp_socket_client=socket(AF_INET,SOCK_STREAM) tcp_socket_client.connect(ip_port) conn_auth(tcp_socket_client) while True: data=input('>>: ').strip() if not data:continue if data == 'quit':break tcp_socket_client.sendall(data.encode('utf-8')) respone=tcp_socket_client.recv(bufsize) print(respone.decode('utf-8')) tcp_socket_client.close() if __name__ == '__main__': ip_port=('127.0.0.1',9999) bufsize=1024 client_handler(ip_port,bufsize)