I have a TCP python client that does request to a TCP server in C++. I have no access to the server so I can't change any of the code on the server part.
The problem is that sometimes the request made by the client doesn't receive any data of the server part so the program gets blocked in the data = sock.recv(1024)
line.
So I wonder how can I solve this problem. I tried putting a conditional after that line if not data is received but there is no way I can pass the data = sock.recv(1024)
line.
try:
data = sock.recv(12) # this always gets data, it is a message send by the server that verifies the connection is alright
print("Received: ", ":".join("{:02x}".format(c) for c in data))
data = sock.recv(1024)
print("Received: ", ":".join("{:02x}".format(c) for c in data))
except IOError as e:
pass
You need to set a timeout for blocking operations using socket.settimeout(N)
or socket.setdefaulttimeout(N)
. In this manner, the operation would fail after N seconds if no data was received.
A second option is to work with non-blocking IO.