I am creating a p2p network using python sockets where each node will have a listening thread and a client side thread that connects to other nodes and listens to other node connections respectively. I created a little buffering protocol on the listening side that will buffer the msgs until it gets all the bytes.
Now, the first issue I was getting was sometimes socket.sendall() would not send all the bytes and in that case there is no way for my listener (on other nodes) to know that this happens and so it would try to buffer msgs until it receives x amt of bytes and then call json.loads() on it, resulting in an exception. To resolve this, I decided to instead use socket.send() in a loop to ensure that all bytes will be sent as below.
while total_sent < msg_len:
sent = recipient_node['socket'].send(byte_msg[total_sent:])
if sent == 0: # disconnected?
pass
total_sent += sent
I get a new bug now which is 'Connection reset by peer' which the stack trace shows happens on the socket.send(). I understand that this is due to some GIL issues and inserting a time.sleep(.0001) or something before sends resolves this issue (kind of), but slows down the p2p network of course.
My question then is, is there a way I can ensure all bytes are delivered using sendall() or is there is a better method using send() and time.sleep(). I'm open to either.