Skip to content

Instantly share code, notes, and snippets.

@ahmedfgad
Created June 23, 2020 19:38
Show Gist options
  • Save ahmedfgad/889e011634327a00ff4e4269d1548d58 to your computer and use it in GitHub Desktop.
Save ahmedfgad/889e011634327a00ff4e4269d1548d58 to your computer and use it in GitHub Desktop.
def recv(connection, buffer_size, recv_timeout):
recv_start_time = time.time() # Time at which last chunk is received from the client.
received_data = b""
while True:
try:
data = connection.recv(buffer_size)
received_data += data
if data == b'': # Nothing received from the client.
received_data = b""
# If still nothing received for a number of seconds specified by the recv_timeout attribute, return with status 0 to close the connection.
if (time.time() - recv_start_time) > recv_timeout:
return None, 0 # 0 means the connection is no longer active and it should be closed.
elif str(data)[-2] == '.':
print("All data ({data_len} bytes) Received.".format(data_len=len(received_data)))
if len(received_data) > 0:
try:
# Decoding the data (bytes).
received_data = pickle.loads(received_data)
# Returning the decoded data.
return received_data, 1
except BaseException as e:
print("Error Decoding the Client's Data: {msg}.\n".format(msg=e))
return None, 0
else:
# In case data are received from the client, update the recv_start_time to the current time to reset the timeout counter.
recv_start_time = time.time()
except BaseException as e:
print("Error Receiving Data from the Client: {msg}.\n".format(msg=e))
return None, 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment