Skip to content

Instantly share code, notes, and snippets.

@VanishMax
Created September 19, 2020 11:24
Show Gist options
  • Save VanishMax/d013afdb5423cb01bc85adb2f518f320 to your computer and use it in GitHub Desktop.
Save VanishMax/d013afdb5423cb01bc85adb2f518f320 to your computer and use it in GitHub Desktop.
Socket file transfer client-server implementation by Maxim Korsunov
import sys
import os
import time
import socket
# Create connection with the server on specific port
sock = socket.socket()
sock.connect((sys.argv[2], int(sys.argv[3])))
address = sys.argv[1]
name = address.split('/')[-1]
with open(address, "rb") as file:
# Show that the file is being sending
size = os.path.getsize(address)
print(f'Start sending file {name} of size {size} bytes')
sock.send(bytes([len(name)]) + name.encode('utf-8'))
count = 0
updated = 0
while True:
# Send by packages of 1024 bytes
blob = file.read(1024)
if not blob:
break
# Keep track of the progress
sock.send(blob)
count += len(blob)
if time.time() - updated > 1:
updated = time.time()
sys.stdout.write("\rSending: {0}/{1} - {2:.1f}%".format(count, size, 100 * count / size))
sys.stdout.write("\rSent: {}/{} - 100%".format(size, size))
sock.close()
print('\nFile successfully sent!')
import socket
import os
# Create socket connection
sock = socket.socket()
sock.bind(("0.0.0.0", 3000))
sock.listen(10)
while True:
connection, address = sock.accept()
# When accept the connection, get filename
nameLen = connection.recv(1)[0]
name = connection.recv(nameLen).decode('utf-8')
print('Receiving the file {} from {}'.format(name, address))
# Check if such filename is already in the server folder
if os.path.exists(name):
splitted = name.split('.')
i = 1
while True:
# Change the name by adding _copy1
tag = '_copy' + str(i) + '.'
newName = splitted[0] + tag + '.'.join(splitted[1:])
if not os.path.exists(newName):
name = newName
break
i += 1
# Save the file
with open(name, 'wb') as file:
while True:
blob = connection.recv(1024)
if not blob:
break
file.write(blob)
connection.close()
sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment