How to Set Timeout on Python's Socket Recv Method

How to set a timeout for recvfrom in socket Python

Use the settimeout function :

import socket

host = socket.gethostname() # Change to the ip address
port = 4000

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(10)
message = input('Send_To_Server: ')

while message != 'endhost':
s.sendto(message.encode('utf-8'), (host, port))
data, addr = s.recvfrom(1024)
data = data.decode('utf-8')
print("Received from server: " + data)
message = input('Send_To_Server: ')
s.close()

This will set a 10s timeout.

Python: fixed wait time for receiving socket data

The link with settimeout() was right. It raises a Exception when timeout.

Set a timeout on blocking socket operations. The value argument can be
a nonnegative floating point number expressing seconds, or None. If a
non-zero value is given, subsequent socket operations will raise a
timeout exception if the timeout period value has elapsed before the
operation has completed. If zero is given, the socket is put in
non-blocking mode. If None is given, the socket is put in blocking
mode.

You need to put your code in a try block, so that the Exception doesn't abort your program.

import socket.timeout as TimeoutException
# set timeout 5 second
clientsocket.settimeout(5)
for i in range(0,10):
sequence_number = i
start = time.time()
clientSocket.sendto("Ping " + str(i) + " " + str(start), server)
# Receive the client packet along with the address it is coming from
try:
message, address = clientSocket.recvfrom(1024)
except TimeoutException:
print("Timeout!!! Try again...")
continue
end = time.time()
if message != '':
print message
rtt = end - start
print "RTT = " + str(rtt)

How to use python socket.settimeout() properly

The timeout applies independently to each call to socket read/write operation. So next call it will be 20 seconds again.

A) To have a timeout shared by several consequential calls, you'll have to track it manually. Something along these lines:

deadline = time.time() + 20.0
while not data_received:
if time.time() >= deadline:
raise Exception() # ...
socket.settimeout(deadline - time.time())
socket.read() # ...

B) Any code that's using a socket with a timeout and isn't ready to handle socket.timeout exception will likely fail. It is more reliable to remember the socket's timeout value before you start your operation, and restore it when you are done:

def my_socket_function(socket, ...):
# some initialization and stuff
old_timeout = socket.gettimeout() # Save
# do your stuff with socket
socket.settimeout(old_timeout) # Restore
# etc

This way, your function will not affect the functioning of the code that's calling it, no matter what either of them do with the socket's timeout.



Related Topics



Leave a reply



Submit