一. 粘包现象
粘包1: 连续的小包,会被优化机制给合并
服务端,客户端
1 # 服务端 2 import socket 3 4 server = socket.socket() 5 ip_port = ('127.0.0.1',8001) 6 7 server.bind(ip_port) 8 server.listen() 9 10 conn,addr = server.accept() 11 12 from_client_msg1 = conn.recv(1024).decode('utf-8') 13 from_client_msg2 = conn.recv(1024).decode('utf-8') 14 15 print('from_client_msg1>>>',from_client_msg1) 16 print('from_client_msg2>>>',from_client_msg2)
1 #=========================================== 2 #客户端 3 import json 4 import socket 5 6 client = socket.socket() 7 ip_port = ('127.0.0.1',8001) 8 client.connect(ip_port) 9 10 client.send(b'12') 11 client.send(b'22')
粘包2: 服务端一次性无法完全接收完客户端发送的数据,第二次接收的时候,
会接收到第一次遗留的内容
服务端,客户端 ipconfig -all
1 import socket 2 import subprocess 3 server = socket.socket() 4 ip_port = ('127.0.0.1',8001) 5 server.bind(ip_port) 6 server.listen() 7 conn,addr = server.accept() 8 while 1: 9 from_client_cmd = conn.recv(1024).decode('utf-8') 10 11 sub_obj = subprocess.Popen( 12 from_client_cmd, 13 shell=True, 14 stdout=subprocess.PIPE, 15 stderr=subprocess.PIPE, 16 ) 17 #subprocess对象.read 得到的结果是bytes类型的 18 cmd_res = sub_obj.stdout.read() 19 print('结果长度>>>',len(cmd_res)) 20 conn.send(cmd_res)
1 import json 2 import socket 3 4 client = socket.socket() 5 ip_port = ('127.0.0.1',8001) 6 client.connect(ip_port) 7 8 9 10 while 1: 11 client_cmd = input('请输入系统指令>>>') 12 client.send(client_cmd.encode('utf-8')) 13 14 from_server_result = client.recv(1024) 15 16 print(from_server_result.decode('gbk'))
二. 解决粘包的方案:
方案1: 先告诉客户端,数据信息的长度,然后等待客户端确认之后,再发送真是内容
服务端,客户端
1 import socket 2 import subprocess 3 server = socket.socket() 4 ip_port = ('127.0.0.1',8001) 5 server.bind(ip_port) 6 server.listen() 7 conn,addr = server.accept() 8 while 1: 9 from_client_cmd = conn.recv(1024).decode('utf-8') 10 11 sub_obj = subprocess.Popen( 12 from_client_cmd, 13 shell=True, 14 stdout=subprocess.PIPE, 15 stderr=subprocess.PIPE, 16 ) 17 #subprocess对象.read 得到的结果是bytes类型的 18 cmd_res = sub_obj.stdout.read() 19 data_len = len(cmd_res) 20 data_len_str = str(data_len) 21 print('结果长度>>>',data_len) 22 23 conn.send(data_len_str.encode('utf-8')) 24 client_stutas = conn.recv(1024).decode('utf-8') 25 if client_stutas == 'ok': 26 27 conn.send(cmd_res) 28 else: 29 print('客户端长度信息没有收到')
1 import json 2 import socket 3 4 client = socket.socket() 5 ip_port = ('127.0.0.1',8001) 6 client.connect(ip_port) 7 8 9 while 1: 10 client_cmd = input('请输入系统指令>>>') 11 client.send(client_cmd.encode('utf-8')) 12 from_server_datalen = client.recv(1024).decode('utf-8') 13 14 client.send(b'ok') 15 16 from_server_result = client.recv(int(from_server_datalen)) 17 18 print(from_server_result.decode('gbk'))
服务端,客户端(升级版,每次发送1024)
1 import socket 2 import subprocess 3 server = socket.socket() 4 ip_port = ('127.0.0.1',8001) 5 data_full_len = 0 #统计发送数据的长度 6 server.bind(ip_port) 7 server.listen() 8 conn,addr = server.accept() 9 while 1: 10 from_client_cmd = conn.recv(1024).decode('utf-8') 11 12 sub_obj = subprocess.Popen( 13 from_client_cmd, 14 shell=True, 15 stdout=subprocess.PIPE, 16 stderr=subprocess.PIPE, 17 ) 18 #subprocess对象.read 得到的结果是bytes类型的 19 cmd_res = sub_obj.stdout.read() 20 data_len = len(cmd_res) #总数据长度 21 data_len_str = str(data_len) 22 print('结果长度>>>',data_len) 23 24 conn.send(data_len_str.encode('utf-8')) 25 client_stutas = conn.recv(1024).decode('utf-8') 26 27 if client_stutas == 'ok': 28 #发送真实数据 29 while data_full_len < data_len: 30 every_send_data = cmd_res[data_full_len:data_full_len + 1024] 31 every_send_datalen = len(every_send_data) 32 conn.send(every_send_data) 33 data_full_len += 1024 34 35 else: 36 print('客户端长度信息没有收到')
1 import json 2 import socket 3 4 client = socket.socket() 5 ip_port = ('127.0.0.1',8001) 6 client.connect(ip_port) 7 all_recv_len = 0 8 all_data_byte = b'' 9 10 while 1: 11 client_cmd = input('请输入系统指令>>>') 12 client.send(client_cmd.encode('utf-8')) 13 from_server_datalen = client.recv(1024).decode('utf-8') 14 all_data_len = int(from_server_datalen) #服务端发送的总数据长度 15 16 client.send(b'ok') 17 18 while all_recv_len < all_data_len: 19 20 from_server_result = client.recv(1024) 21 every_recv_len = len(from_server_result) #每次接受的数据长度 22 all_recv_len += every_recv_len 23 all_data_byte += from_server_result 24 25 26 print(all_data_byte.decode('gbk'))
方案2: 通过struct 模块,将要发送的真实数据的长度进行打包,打包成4个字节,和真
实数据的长度,根据这个长度在进行数据的接收
服务端,客户端
1 import socket 2 import subprocess 3 import struct 4 server = socket.socket() 5 ip_port = ('127.0.0.1',8001) 6 data_full_len = 0 #统计发送数据的长度 7 server.bind(ip_port) 8 server.listen() 9 conn,addr = server.accept() 10 while 1: 11 from_client_cmd = conn.recv(1024).decode('utf-8') 12 13 sub_obj = subprocess.Popen( 14 from_client_cmd, 15 shell=True, 16 stdout=subprocess.PIPE, 17 stderr=subprocess.PIPE, 18 ) 19 #subprocess对象.read 得到的结果是bytes类型的 20 cmd_res = sub_obj.stdout.read() 21 data_len = len(cmd_res) #总数据长度 22 data_len_str = str(data_len) 23 print('结果长度>>>',data_len) 24 25 #将真实数据长度打包成4个字节的数据 26 struct_data_len = struct.pack('i',data_len) 27 28 conn.send(struct_data_len + cmd_res)
1 import json 2 import socket 3 import struct 4 client = socket.socket() 5 ip_port = ('127.0.0.1',8001) 6 client.connect(ip_port) 7 all_recv_len = 0 8 all_data_byte = b'' 9 10 while 1: 11 client_cmd = input('请输入系统指令>>>') 12 client.send(client_cmd.encode('utf-8')) 13 #先接收4个字节,这4个字节是真实数据长度加工成的 14 recv_data_len = client.recv(4) 15 #将4个字节长度的数据,解包成后面真实数据的长度 16 real_data_len = struct.unpack('i',recv_data_len)[0] 17 18 print(real_data_len) 19 20 server_result = client.recv(real_data_len) 21 22 print(server_result.decode('gbk'))
struct演示
1 import struct 2 3 num = 1288888882 4 5 num_str = struct.pack('i',num) 6 print(num_str,len(num_str)) 7 8 a = struct.unpack('i',num_str)[0] 9 print(a)
获取缓冲区大小的方法
1 import socket 2 from socket import SOL_SOCKET,SO_REUSEADDR,SO_SNDBUF,SO_RCVBUF 3 sk = socket.socket(type=socket.SOCK_DGRAM) 4 # sk.setsockopt(SOL_SOCKET,SO_RCVBUF,80*1024) 5 sk.bind(('127.0.0.1',8090)) 6 print('>>>>', (sk.getsockopt(SOL_SOCKET, SO_SNDBUF))/1024) 7 print('>>>>', sk.getsockopt(SOL_SOCKET, SO_RCVBUF))
合法性链接验证
服务端,客户端
1 from socket import * 2 import hmac,os 3 4 secret_key=b'Jedan has a big key!' 5 def conn_auth(conn): 6 ''' 7 认证客户端链接 8 :param conn: 9 :return: 10 ''' 11 print('开始验证新链接的合法性') 12 msg=os.urandom(32)#生成一个32字节的随机字符串 13 conn.sendall(msg) 14 h=hmac.new(secret_key,msg) 15 digest=h.digest() 16 respone=conn.recv(len(digest)) 17 return hmac.compare_digest(respone,digest) 18 19 def data_handler(conn,bufsize=1024): 20 if not conn_auth(conn): 21 print('该链接不合法,关闭') 22 conn.close() 23 return 24 print('链接合法,开始通信') 25 while True: 26 data=conn.recv(bufsize) 27 if not data:break 28 conn.sendall(data.upper()) 29 30 def server_handler(ip_port,bufsize,backlog=5): 31 ''' 32 只处理链接 33 :param ip_port: 34 :return: 35 ''' 36 tcp_socket_server=socket(AF_INET,SOCK_STREAM) 37 tcp_socket_server.bind(ip_port) 38 tcp_socket_server.listen(backlog) 39 while True: 40 conn,addr=tcp_socket_server.accept() 41 print('新连接[%s:%s]' %(addr[0],addr[1])) 42 data_handler(conn,bufsize) 43 44 if __name__ == '__main__': 45 ip_port=('127.0.0.1',9999) 46 bufsize=1024 47 server_handler(ip_port,bufsize)
1 from socket import * 2 import hmac,os 3 4 secret_key=b'Jedan has a big key!' 5 def conn_auth(conn): 6 ''' 7 验证客户端到服务器的链接 8 :param conn: 9 :return: 10 ''' 11 msg=conn.recv(32) 12 h=hmac.new(secret_key,msg) 13 digest=h.digest() 14 conn.sendall(digest) 15 16 def client_handler(ip_port,bufsize=1024): 17 tcp_socket_client=socket(AF_INET,SOCK_STREAM) 18 tcp_socket_client.connect(ip_port) 19 20 conn_auth(tcp_socket_client) 21 22 while True: 23 data=input('>>: ').strip() 24 if not data:continue 25 if data == 'quit':break 26 27 tcp_socket_client.sendall(data.encode('utf-8')) 28 respone=tcp_socket_client.recv(bufsize) 29 print(respone.decode('utf-8')) 30 tcp_socket_client.close() 31 32 if __name__ == '__main__': 33 ip_port=('127.0.0.1',9999) 34 bufsize=1024 35 client_handler(ip_port,bufsize)