Feb-01-2018, 11:40 AM
An implementation which uses a buffer and memoryview:
The socket object has also the function sendfile which takes a fileobject. Maybe this is the fastest implementation. I never tried it.
import socket host = '127.0.0.1' port = 1337 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # use TCP for data transmission sock.connect((host, port)) buffer = bytearray(1024**2) # 1MiB view = memoryview(buffer) with open(file, 'rb') as fd: while True: readlen = fd.readinto(buffer) # buffer is reused if not readlen: break sock.send(view[:readlen] # sends read data from memoryview to socket sock.close()The buffer is reused for the chunks. The method readinto of a fileobject, puts the data into the buffer and returns the amount of data, which has been written to the buffer. The memoryview is just a method to have fast access on slices.
The socket object has also the function sendfile which takes a fileobject. Maybe this is the fastest implementation. I never tried it.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!