recv and recvfrom, socket programming using python

前端 未结 3 2046
慢半拍i
慢半拍i 2021-01-02 18:04

i am new to python and new to socket programming as well.

I am confused about about socket.recvfrom() and socket.recv()

I understan

3条回答
  •  一生所求
    2021-01-02 19:01

    I think people usually use recvfrom for UDP. Because in TCP, once the connection gets established, the address information does not change and hence recvfrom always returns None for connection-information field.

    And in the above code, it will error out in this line:

    message2, clientAddress2 = serverSocketTCP.recv(1024)
    

    Because: recvfrom() returns (data, connection_information), and recv() returns just the data. So it will raise ValueError because you are trying to unpack a non-tuple value.

    1024, or 2048 just defines the buffer size but it does not wait for exactly that much amount of data before returning. For example:

    #One side, 'receiver' is a socket
    receiver.recv(2048)
    
    #Second side, 'sender' is a socket
    sender.send('abc'.encode('utf-8'))
    

    Clearly the data sent by 'sender' is much less than 2048 bytes but the 'recv' call will return immediately after it receives the data sent to it from 'sender'

提交回复
热议问题