Advertisement
Guest User

Untitled

a guest
Apr 6th, 2017
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. ######## SERVIDOR ########
  2.  
  3. import socket, json
  4.  
  5. def get_file(conn, info):
  6. remaining = info['size']
  7. file_bin = b''
  8. while remaining > 0:
  9. try:
  10. package = conn.recv(2048)
  11. except Exception as err:
  12. return None
  13. file_bin += package
  14. remaining -= len(package)
  15. return file_bin
  16.  
  17. host, port = ('', 9005)
  18. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
  19. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  20. sock.bind((host, port))
  21. sock.listen(5)
  22. while True:
  23. conn, addr = sock.accept()
  24. print('conn', addr)
  25. info_bin = b''
  26. while True:
  27. c = conn.recv(1)
  28. if c == b'\x00':
  29. break
  30. info_bin += c
  31. info = json.loads(info_bin.decode())
  32. file_bin = get_file(conn, info)
  33. if file_bin is not None:
  34. dest = 'files/{}'.format(info['name'])
  35. with open(dest, 'wb') as f:
  36. f.write(file_bin)
  37. print('success on receiving and saving {} for {}'.format(info['name'], conn.getpeername()))
  38. conn.close()
  39.  
  40.  
  41.  
  42. ########## CLIENTE ###########
  43.  
  44. import socket, json
  45.  
  46. f = input('escreva o nome do ficheiro')
  47. f_bin = open(f, 'rb').read()
  48. info = {'name': f, 'size': len(f_bin)}
  49. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  50. s.connect(('89.115.59.255', 8080))
  51. s.send(json.dumps(info).encode())
  52. s.send(b'\x00') # byte nulo para sabermos do lado servidor que ja recebemos a informcao
  53. total_sent = 0
  54. s.sendall(f_bin)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement