Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. import socket # Import socket module
  2. from pathlib import Path
  3. import time
  4.  
  5.  
  6. port = 8080 # Reserve a port for your service every new transfer wants a new port or you must wait.
  7. s = socket.socket() # Create a socket object
  8. host = "" # Get local machine name
  9. s.bind((host, port)) # Bind to the port
  10. s.listen(5) # Now wait for client connection.
  11.  
  12. print('Listening...')
  13.  
  14.  
  15. while True:
  16. conn, addr = s.accept() # Establish connection with client.
  17. print('New connection!', addr)
  18. filename = conn.recv(256).decode()
  19. print('Server received', filename)
  20.  
  21. time.sleep(2)
  22.  
  23. file_check = Path('received/' + filename)
  24. if not file_check.is_file():
  25. conn.send(b'Got it, saving file as ' + bytes(filename, encoding='utf8'))
  26. print('msg sent')
  27. file = open('received/' + filename, 'wb')
  28. while True:
  29. buff = conn.recv(2)
  30. if buff.decode() == 'ok':
  31. conn.close()
  32. break
  33. buff = conn.recv(1024)
  34. file.write(buff)
  35.  
  36. file.close()
  37. else:
  38. print('file found')
  39. i = 1
  40. filename = filename.split('.')
  41. name = filename[0] + '_copy' + str(i) + '.' + '.'.join(str(x) for x in filename[1:])
  42. while Path('received/' + name).is_file():
  43. i += 1
  44. name = filename[0] + '_copy' + str(i) + '.' + '.'.join(str(x) for x in filename[1:])
  45.  
  46. conn.send(b'That file already exists. Saving as ' + bytes(name, encoding='utf8'))
  47. file = open('received/' + name, 'wb')
  48. while True:
  49. buff = conn.recv(2)
  50. if buff == b'ok' or buff == b'':
  51. conn.close()
  52. break
  53. buff = conn.recv(1024)
  54. file.write(buff)
  55.  
  56. file.close()
  57.  
  58. print('Done receiving')
  59. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement