This article mainly describes three methods for python network programming to call the recv function to receive data in full, interested friends can refer to the recent development of a common tcpclient testing tool for network programming using python. In network programming using socket, how to determine whether a packet sent by the peer end is received is a problem that must be considered in socket network development. Here, we will briefly introduce three common methods to identify the completion of data reception:
1. basic data receiving method:
When the basic data receiving method is used, an empty string is received when the connection is disconnected from the service socket. Therefore, you can add a loop in the program to receive data until the data sender closes the socket connection. Application scenario: the client and server connections are short links (that is, the connection will be closed after a socket communication ). The code is as follows:
import socket,struct,sys,timePort=22220#assume a socket disconnect (data returned is empty string) means all data was #done being sent.def recv_basic(the_socket): total_data=[] while True: data = the_socket.recv(20480) if not data: break total_data.append(data) return ''.join(total_data)
2. tail identification method
Obtain the complete data packet by searching for the tail ID string in the received protocol data. Applicable scenario: the received protocol data contains the relevant tail ID. The code is as follows:
End='something useable as an end marker'def recv_end(the_socket): total_data=[];data='' while True: data=the_socket.recv(8192) if End in data: total_data.append(data[:data.find(End)]) break total_data.append(data) if len(total_data)>1: #check if end_of_data was split last_pair=total_data[-2]+total_data[-1] if End in last_pair: total_data[-2]=last_pair[:last_pair.find(End)] total_data.pop() break return ''.join(total_data)
3. load length method
That is, the length of the valid message is determined by the load length value in the protocol data. applicable scenarios: the protocol data contains the load Protocol field. This method is also a common and common method, but it needs to parse data while receiving data. The code is as follows:
def recv_size(the_socket): #data length is packed into 4 bytes total_len=0;total_data=[];size=sys.maxint size_data=sock_data='';recv_size=8192 while total_len
4: size_data+=sock_data size=struct.unpack('>i', size_data[:4])[0] recv_size=size if recv_size>524288:recv_size=524288 total_data.append(size_data[4:]) else: size_data+=sock_data else: total_data.append(sock_data) total_len=sum([len(i) for i in total_data ]) return ''.join(total_data)
The above is a detailed explanation of the three methods for python network programming to call the recv function to completely receive data. For more details, please refer to other related articles in the first PHP community!