Skip to content

Instantly share code, notes, and snippets.

@ahmedfgad
Created June 23, 2020 19:39
Show Gist options
  • Save ahmedfgad/6f8abcde7d7b951fadba4f4a58911c39 to your computer and use it in GitHub Desktop.
Save ahmedfgad/6f8abcde7d7b951fadba4f4a58911c39 to your computer and use it in GitHub Desktop.
import socket
import pickle
import time
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
soc = socket.socket()
print("Socket is created.")
soc.bind(("localhost", 10000))
print("Socket is bound to an address & port number.")
soc.listen(1)
print("Listening for incoming connection ...")
connected = False
accept_timeout = 10
soc.settimeout(accept_timeout)
try:
connection, address = soc.accept()
print("Connected to a client: {client_info}.".format(client_info=address))
connected = True
except socket.timeout:
print("A socket.timeout exception occurred because the server did not receive any connection for {accept_timeout} seconds.".format(accept_timeout=accept_timeout))
received_data = b''
if connected:
while True:
recv_start_time = time.time()
time_struct = time.gmtime()
date_time = "Waiting to Receive Data Starting from {day}/{month}/{year} {hour}:{minute}:{second} GMT".format(year=time_struct.tm_year, month=time_struct.tm_mon, day=time_struct.tm_mday, hour=time_struct.tm_hour, minute=time_struct.tm_min, second=time_struct.tm_sec)
print(date_time)
recv_timeout = 5
received_data, status = recv(connection, 8, recv_timeout)
print("Received data from the client: {received_data}".format(received_data=received_data))
if status == 0:
connection.close()
print("Connection Closed either due to inactivity for {recv_timeout} seconds or due to an error.".format(recv_timeout=recv_timeout), end="\n\n")
break
msg = "Reply from the server."
msg = pickle.dumps(msg)
connection.sendall(msg)
print("Server sent a message to the client.")
soc.close()
print("Socket is closed.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment