I am writing python code to send and receive data, using TCP connection. But I have a problem which I find very confusing. When I call recv method on the server socket once and then send, it works fine. However, when I call recv method twice on the server socket and then send, the client does not receive anything from the server but just hangs.
Here is the server code:
server = socket.socket()
server.bind(('0.0.0.0', 9999))
server.listen(5)
while True:
client, addr = server.accept()
client.recv(1024)
# works if the line below is commented out
client.recv(1024)
client.send(b'ACK!')
client.close()
Here is the client code:
client = socket.socket()
client.connect(('127.0.0.1', 9999))
client.send(bytes(sys.stdin.read(), encoding='utf-8'))
print(client.recv(4096).decode('utf-8'))
Actually, I plan to use a loop with the recv method in the server code. But the send method does not work if the recv method is called more than once. Why does this happen?
client.recv(1024)is probably blocked waiting for data. What did you expect to happen?recvwill receive nothing) and then send data. But as you said, the server might be waiting for data in the second call ofrecv. I think I might need to usesettimeout. Thank you for the answer.