0

I am working on socket programming in python. Using ESP python i have created a socket to server and sending a request (in API packet format, according to server code it will respond). In receiving socket, i need to check the data(if data is received, it need continue to next operation. If not, i need to send request once again). sending is okay. In receiving socket, if it is not receiving data, it is not going to next instruction.. please help me out.

code:

try:

    s = socket(AF_INET, SOCK_DGRAM)
    print "socket created"

except socket.error:

    print "failed to create socket"
    sys.exit()

sending data:

s.sendto("packet of data", 0, (HOST,PORT))

In receiving:

recvpack, payload=s.recvfrom(1024)

if not recvpack:

    s.sendto("packet of data", 0, (HOST,PORT))

elif(recvpack[]="packet of data"):

    pass # continue to next operations..

In the above receiving statement, if recvfrom() in not getting anydata, how to check recvpack and get back to next operations.. If socket.settimeout() or socket.setblocking() is the solution, how to use these..

Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
varma v
  • 1
  • 1
  • 3

1 Answers1

1

If you don't mind a blocking call, I usually use settimeout to wait for a message. settimeout will raise an exception if it doesn't receive a message in time.

So basically you could do something like this:

s.settimeout(1)
try:
    recvpack, payload = s.recvfrom(1024)
except error:
    recvpack = None
if recvpack is not None:
    ...

Source : https://docs.python.org/2/library/socket.html#socket.socket.settimeout

Jawad
  • 4,457
  • 1
  • 26
  • 29