Advertisement
DeaD_EyE

minimal sendfile example python

Feb 12th, 2018
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. # client recv_into
  2. import socket
  3.  
  4.  
  5. addr = ('127.0.0.1', 8080)
  6. file = 'test.bin'
  7. data = bytearray(8128)
  8. view = memoryview(data)
  9. with socket.socket() as sock:
  10.     sock.connect(addr)
  11.     print('Connected')
  12.     with open(file, 'wb') as fd:
  13.         while True:
  14.             size = sock.recv_into(data)
  15.             if not size:
  16.                 print('EOF')
  17.                 break
  18.             fd.write(view[:size])
  19. print('{} has been written.'.format(file))
  20.  
  21.  
  22.  
  23. ################################################################
  24.  
  25.  
  26. # server sendfile
  27. import threading
  28. import socket
  29.  
  30.  
  31. def handler(sock, file):
  32.     with open(file, 'rb') as fd:
  33.         sock.sendfile(fd)
  34.         sock.close()
  35.  
  36. addr = ('127.0.0.1', 8080)
  37. file_to_send = 'tunnel.sh'
  38.  
  39. with socket.socket() as sock:
  40.     sock.bind(addr)
  41.     sock.listen(5)
  42.     while True:
  43.         client_sock, client_addr = sock.accept()
  44.         threading.Thread(target=handler, args=(client_sock, file_to_send)).start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement