0

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)
    file.write(buffer)

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

Adrian Muljadi
  • 168
  • 1
  • 15
  • 1
    `socket.recv` is a blocking call. It does not return 0 bytes if nothing is sent. If TCP is set to non-blocking, then it's a duplicate of http://stackoverflow.com/questions/16745409/what-does-pythons-socket-recv-return-for-non-blocking-sockets-if-no-data-is-r – Jean-François Fabre Sep 03 '16 at 10:12
  • What happens when client tears down connection? what will `socket.recv` return then? – Adrian Muljadi Sep 03 '16 at 10:35
  • are you using blocking or non-blocking calls? – Jean-François Fabre Sep 03 '16 at 10:37
  • I'm not so sure myself, but I think I see what you mean. I just created a sample client server application, using blocking sockets if the client hasn't called `socket.close()`, `socket.recv()` just blocks. But as soon as client calls `socket.close()`, `socket.recv()` returns an empty bytearray Am I getting the right idea? – Adrian Muljadi Sep 03 '16 at 10:54

1 Answers1

0

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)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219