28 粘包
一粘包现象:
粘包1:连续的小包,会被优化机制给合并
粘包2:服务端一次性无法完全就收完客户端发送的数据,第二再次接收的时候,会接收到第一次遗留的内容
解决粘包的方案:
方案1:先告诉客户端,数据信息的长度,然后等客户端确认之后,再发送真实内容
方案2:通过struct模块,将要发送的真实数据的长度进行打包,打包成4个字节,和真实数据一起一次性发送个客户端.
客户端取出前4个字节,通过struct解包获得后面真实数据的长度,根据这个长度再进行数据的接受
黏包现象只发生在tcp协议中:
1.从表面上看,黏包问题主要是因为发送方和接收方的缓存机制、tcp协议面向流通信的特点。
2.实际上,主要还是因为接收方不知道消息之间的界限,不知道一次性提取多少字节的数据所造成的。
二.struct 打包模块
import struct num = 12235667 num_str = struct.pack('i',num) print(num_str) #b'\x0c\x00\x00\x00' print(len(num_str)) a = struct.unpack('i',num_str)[0] #12235667 print(a) #(12235667,) #
#服务端 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) print('from_client_msg2>>>',from_client_msg2) #客户端 import json 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() 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'))
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'))
合法性连接
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)
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)
获取缓存区大小
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))
有疑问可以加wx:18179641802,进行探讨