Reputation: 815
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?
Upvotes: 2
Views: 6784
Reputation: 2745
None of the answers currently given will solve your problem. Your socket() construction is fine with default parameters, and the number of sends and receives doesn't matter at all. The real answer is this:
When you recv(1024), you're going to get at least one, and at most 1024 bytes. You probably know the latter, but the former might be a surprise. It is a consequence of how network works. recv must block (unless the socket is in nonblocking mode) until it gets something, and that something will be at least one byte. So if there's nothing to read, recv will hang. It can't detect the difference between that situation and the network simply being slow.
If you have further questions, feel free to ask.
Upvotes: 0
Reputation: 149
I do not really think that is your main problem. You also did not specify the connection type (tcp or udp).
For TCP you call socket.socket(socket.SOCK_STREAM, socket.AF_INET)
For UDP you call socket.socket(socket.SOCK_STREAM, socket.SOCK_DGRAM)
I do not know if this will fix your problem, but I hope so.
Upvotes: 0
Reputation: 960
client.recv(1024) does not mean block until you recv 1024 bytes, you're not guaranteed to get 1024 bytes with this call, you're only guaranteed to get no more than 1024 bytes. You could get 0, 9, 25, etc. bytes, just no more than 1024. The real issue is that your sequence isn't quite right. On the server side you're calling recv twice and then send, on the client side you're calling send once then recv. If you're going to recv twice on the server then you need to send twice on the client.
The issue is that you're being blocked because you're not sending ANY data, when it's expecting something.
Upvotes: 3