问题
I am trying to get data from a TCP Connection (client side only) using Python as programming language,
However, I could see that all data are not received in once and are cut in the middle of the receiving process ... I could see on forums that TCP does not send data in the correct order (it is a bit random, link: Python socket receive - incoming packets always have a different size), am I wrong ?
My question is if there is anyway to make sure that I correctly received all data?
Thanks in advance for your help and replies,
PS: I already increased the buffer size of socket.recv(), but still facing the same issue ... And I am only working under CentOS
EDIT: (couldn't reply to my own question :( Still beginner on this forum :) )
Hi,
Thanks a lot for your reply, indeed I don't have to worry about the TCP connection :)
After investigating more, I could finally find the solution ... (I was searching for a few days before posting my question here),
If anyone needs an answer, in python you must wait for the full message, otherwise the message can be cut, so this means:
data = s.recv(1024, socket.MSG_WAITALL) --> 's' is a socket object created in the python code,
Kind regards
回答1:
using the sockets API, you do not have to worry about TCP (the ordering, retransmissions and whatnot), it's all been taken care of by the OS. The only thing is that socket.recv()
will return at most n bytes. This means that it is not guaranteed that you will receive n bytes at each blocking read. So, you must read in a loop until you have received the desired amount of bytes.
来源:https://stackoverflow.com/questions/23732930/how-to-check-if-all-data-are-received-with-a-tcp-socket-in-python