Ending a Python TCP connection
<p>I'm new to socket programming and currently trying to learn it using Python</p>

<p>Currently I'm confused over when a receiving application knows when the sending application finished sending data.</p>

<p>For example, in Python, reading from a TCP socket is done using </p>

<pre><code>socket.recv(bufsize [, flags])
</code></pre>

<p>which returns a bytearray of the data received. if there is more data (e.g. in the buffer), we simply call this method again. My current pattern looks like this.</p>

<pre><code>while True: 
    buffer = socket.recv(1024)
    file.write(buffer)
</code></pre>

<p>However, how do I know when the peer has stopped sending data and exit the loop? Because if this method returns 0 bytes, there's 2 possibilities:</p>

<ol>
<li><p>the buffer is empty, and the peer is still sending data</p></li>
<li><p>the buffer is empty, the peer has closed </p></li>
</ol>

<p>My question is, how does the receiving application differentiate between scenario 1 and 2</p>

<p>buffer will return an empty array only if the client closes the connection.</p>

<p>If the client sends nothing, since TCP call is blocking in your case, the program stays blocked forever on <code>recv</code> until data arrives or connection is closed (in which case data arrives empty).</p>

<p>(It's the same thing when you read a file on disk: you read data until data returns empty string/byte array: then you know you reached the end of the file)</p>

python sockets networking tcp