Some sources say ... But other sources say ... message ...
Both sources are wrong.
The argument for the recv
is the maximum number of bytes one want to read at once.
With an UDP socket this is the message size one want to read or larger, but a single recv
will only return a single message anyway. If the given size is smaller than the message it will be pruned and the rest will be discarded.
With a TCP socket (the case you ask about) there is no concept of a message in the first place since TCP is a byte stream only. recv
will simply return the number of bytes available for read, up to the given size. Specifically a single recv
in a TCP receiver does not not need to match a single send
in the sender. It might match and it often will match if the amount of data is small, but there is no guarantee and one should never rely on it.
... message0 = str(client.recv(5).decode('utf-8'))
Note that calling decode('utf-8')
directly on the data returned by recv
is a bad idea. One first need to be sure that all the expected data are read and only then call decode('utf-8')
. If only part of the data are read the end of the read data could be in the middle of a character, since a single character in UTF-8 might be encoded in multiple bytes (everything except ASCII characters). If decode('utf-8')
is called with an incomplete encoded character it will throw an exception and your code will break.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…