adrian muljadi adrian muljadi - 1 month ago 7x
Python Question

Ending a Python TCP connection

I'm new to socket programming and currently trying to learn it using Python

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

For example, in Python, reading from a TCP socket is done using

socket.recv(bufsize [, flags])

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.

while True:
buffer = socket.recv(1024)

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:

  1. the buffer is empty, and the peer is still sending data

  2. the buffer is empty, the peer has closed

My question is, how does the receiving application differentiate between scenario 1 and 2


buffer will return an empty array only if the client closes the connection.

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

(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)