Skip to content

Instantly share code, notes, and snippets.

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

  • Save shivamS21/08adee6a70684f392d9660156a32355e to your computer and use it in GitHub Desktop.

Select an option

Save shivamS21/08adee6a70684f392d9660156a32355e 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment