I am new to python and socket programming, and I'm confused about about usage for socket.recvfrom()
and socket.recv()
. I understand that people usually use recvfrom()
for UDP and recv()
for TCP.
For example:
serverSocketUDP = socket(AF_INET, SOCK_DGRAM)
serverSocketTCP = socket(AF_INET, SOCK_STREAM)
#... define server...
#...
message, clientAddress = serverSocketUDP.recvfrom(2048) #why 2048 for UDP? Ive seen several examples like this.
message2 = serverSocketTCP.recv(1024) #Again, why 1024 for TCP?
As seen in the example above, what I am confused about is the numbers. Why 2048 and 1024 for different protocols? What do these numbers represent?
Why 2048 and 1024 for different protocols?
Those are very arbitrary numbers and depend on the protocol being implemented. And even though the TCP number works, the UDP number you give is very likely wrong.
TCP implements a stream protocol that you can read in any sized chunk you want. You could do recv(1)
to get a byte at a time or recv(100000)
if you want to grab large chunks. recv
is free to return smaller blocks that you ask for, so you may get a different size than you want. 1024 is pretty small, you could read much larger chunks without a problem.
UDP implements a message protocol. You have to ask for enough bytes to cover the entire message or it will be dropped. What that size is depends on the protocol. Its common for protocols to limit messages to 1500 (the max size of a standard ethernet packet) but it could be anything up to 65535. Check the actual protocol specs for maximums.