pythonsocketsudpbufferingpython-sockets

Why does a socket connection buffer so much data?


I have one program sending data with 10Hz frequency.

import socket
import time


if __name__ == '__main__':
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('127.0.0.1', 19080))

    while True:
        data = time.time()
        sock.sendto(str(data).encode(), ('127.0.0.1', 9090))
        time.sleep(0.1)

And second program recieving data, with delay (1Hz):

import socket
import time


if __name__ == '__main__':
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('127.0.0.1', 9090))

    while True:
        data = time.time()
        print(time.time(), sock.recv(100))
        time.sleep(1)

After a while, output is:

1600859111.7595737 b'1600858988.4863389'
1600859112.760249 b'1600858988.5863452'
1600859113.760647 b'1600858988.6864707'
1600859114.761207 b'1600858988.7871313'
1600859115.761991 b'1600858988.8875835'

You can see big diffrence in times when data is received(right) and when is send(left). Why it's so much data buffered, and how can I get rid of this? I want possible newest frames, not the buffered ones.


Solution

  • I found the anserw. I had to set socket option for the size of the input buffer.

       sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
    

    Set it to 0, for max effinency.