Assuming you don’t want to end the connection, the simplest solution is a fixed length message: The sending code here is usable for almost any messaging scheme - in Python you send strings, and you can use len() to determine its length (even if it has embedded$_{\0}$characters). It’s mostly the receiving code that gets more complex. (And in C, it’s not much worse, except you can’t use$_{strlen}$if the message has embedded$_{\0}$ s.) The easiest enhancement is to make the first character of the message an indicator of message type, and have the type determine the length. Now you have two$_{recv}$s - the first to get (at least) that first character so you can look up the length, and the second in a loop to get the rest. If you decide to go the delimited route, you’ll be receiving in some arbitrary chunk size, (4096 or 8192 is frequently a good match for network buffer sizes), and scanning what you’ve received for a delimiter. One complication to be aware of: if your conversational protocol allows multiple messages to be sent back to back (without some kind of reply), and you pass$_{recv}$an arbitrary chunk size, you may end up reading the start of a following message. You’ll need to put that aside and hold onto it, until it’s needed. Prefixing the message with its length (say, as 5 numeric characters) gets more complex, because (believe it or not), you may not get all 5 characters in one$_{recv}$. In playing around, you’ll get away with it; but in high network loads, your code will very quickly break unless you use two$_{recv}$loops - the first to determine the length, the second to get the data part of the message. Nasty. This is also when you’ll discover that$_{send}$ does not always manage to get rid of everything in one pass. And despite having read this, you will eventually get bit by it! In the interests of space, building your character, (and preserving my competitive position), these enhancements are left as an exercise for the reader. Lets move on to cleaning up. 4 classMySocket : """demonstration class only - coded for clarity, not efficiency """ def __init__ (self, sock= None ): if sock is None : self.sock =socket.socket( socket.AF_INET, socket.SOCK_STREAM) else : self.sock =sock def connect(self, host, port): self.sock.connect((host, port)) def mysend(self, msg): totalsent=0 while totalsent<MSGLEN: sent =self.sock.send(msg[totalsent:]) if sent ==0: raise RuntimeError("socket connection broken") totalsent=totalsent+sent def myreceive(self): chunks =[] bytes_recd=0 while bytes_recd<MSGLEN: chunk =self.sock.recv( min(MSGLEN -bytes_recd,2048 )) if chunk ==b'': raise RuntimeError("socket connection broken") chunks.append(chunk) bytes_recd=bytes_recd+len(chunk) return b''.join(chunks)