drdot
drdot

Reputation: 3347

Python: fixed wait time for receiving socket data

I wrote a udp server and client. The client send simple udp messages to the server and the server will respond. The server will randomly drop some response packets. In my client side code, I wrote the following line

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
  message, address = clientSocket.recvfrom(1024)
  end = time.time()
  if message != '':
    print message
    rtt = end - start
    print "RTT = " + str(rtt)

The following line stuck there if the server drop the response.

message, address = clientSocket.recvfrom(1024)

I tried the timeout method here: Socket recv - limited wait time
But the timeout will abort the whole client program. I just want the client to wait for 5 second and then continue to send the next packet if the last response is not received (dropped by the server). How can I set a wait time in the client?

Upvotes: 3

Views: 18326

Answers (2)

ققنوس
ققنوس

Reputation: 15

just use this

readable, empty, empt = select.select(servers, [], [] , 10 ) # wait just 10sec 
ready_server = readable[0]

Upvotes: 0

qvpham
qvpham

Reputation: 1938

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)

Upvotes: 8

Related Questions