Skip to content

Instantly share code, notes, and snippets.

@shivamS21
Created September 29, 2020 20:20
Show Gist options
  • Select an option

  • Save shivamS21/8b3a5bd5456bfc9db1117494377fafd1 to your computer and use it in GitHub Desktop.

Select an option

Save shivamS21/8b3a5bd5456bfc9db1117494377fafd1 to your computer and use it in GitHub Desktop.
//this is server's side code where I am recieving the files and trying to save them into a folder names 'serv'
from socket import *
import os
CHUNKSIZE = 1_000_000
server = socket()
server.bind(('localhost',9999))
server.listen(3)
os.makedirs('serv',exist_ok=True)
with server,server.makefile('rb') as serverfile:
while True:
print('Waiting for a client...')
client, address = server.accept()
print(f'Client joined from {address}')
with client:
raw = serverfile.readline()
if not raw:
break
filename = raw.strip().decode()
length = int(serverfile.readline())
print(f'Downloading {filename}...\n Expecting {length:,} bytes...', end='', flush=True)
path = os.path.join('serv', filename)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'wb') as f:
while length:
chunk = min(length, CHUNKSIZE)
data = serverfile.read(chunk)
if not data: break
f.write(data)
length -= len(data)
else: # only runs if while doesn't break and length==0
print('Complete')
continue
print('Incomplete')
break
server.close()
// this is client side code where the files are send from a folder names electro
from socket import *
import os
import tqdm
CHUNKSIZE = 1_000_000
buffer_size = 4096
# Make a directory for the received files.
sock = socket()
sock.connect(('localhost',9999))
while True:
print("ready to send files...")
for path, dirs, files in os.walk('electro'):
for file in files:
filename = os.path.join(path, file)
relpath = os.path.relpath(filename, 'electro')
filesize = os.path.getsize(filename)
print(f'Sending {relpath}')
with open(filename, 'rb') as f:
sock.sendall(relpath.encode() + b'\n')
sock.sendall(str(filesize).encode() + b'\n')
# Send the file in chunks so large files can be handled.
while True:
data = f.read(CHUNKSIZE)
if not data: break
sock.sendall(data)
print('Done...')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment