Since TCP is a streaming protocol (as specified in SOCK_STREAM
), there are no fixed boundaries or message packets, and you can never be sure that you get everything with just one recv
call. You just need to call recv
in the loop, add to the buffer, and exit the loop if you think you have enough. Most text protocols use either a new line to indicate that the reading is done, and to do something with the received data. Other protocols use different characters or byte sequences.
In your case, if there is no special character saying that the end of the current data has been reached, you have two solutions:
Use timeout: if new data has not been received for some time, print it.
Non-blocking sockets: just read through the loop by adding data to the internal buffer. When the recv
call throws an error with errno
equal to errno.EWOULDBLOCK
, then there is no longer any need to read and print the received data.
Alternative 2, along with the select
package, is probably the best way to go.
Edit
Here is a simple example of what I mean. This probably won't work, and you need some kind of customization, but hopefully this is enough for you.
# Need to import: package socket, package select, package errno
source share