Python Bidirectional Tcp Socket Hanging On Socket.recv
Solution 1:
From my understanding (epiphany here), the main problem is that recv
inside recvall
is only concerned with retrieving the stream (in the same way send
is only concerned with sending the stream), it has no concept of a "message" and therefore cannot know when to finish reading. It read all the bytes and did not return any additional bytes, but that is NOT a signal that the message is finished sending, there could be more bytes waiting to be sent and it would not be safe to assume otherwise.
This requires us to have an explicit indicator for when to stop reading. recv
and send
are only concerned with managing the stream and therefore have no concept of a message (our "unit"). This article has some great solutions to this problem. Since I am sending fixed-length messages, I opted to check that the length is as expected before finishing recv
. Here is the updated version of recvall
, note MSG_LENGTH
must be defined and enforced in order for recvall
to not block the socket.
def recvall(socket):
data = ''while len(data) < MSG_LENGTH:
packet = socket.recv(BUFFER_SIZE)
if not packet: breakdata += packet
returndata
Bidirectional communication now works, the only catch being the client and server must know the length of the message they will receive, again this is not an issue in my case. This is all new to me so someone please correct me on terminology and concepts.
Post a Comment for "Python Bidirectional Tcp Socket Hanging On Socket.recv"