-
Notifications
You must be signed in to change notification settings - Fork 281
/
tcp_file_server.py
40 lines (33 loc) · 1.36 KB
/
tcp_file_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import socketserver
import threading
import time
import sys
class RequestHandler(socketserver.StreamRequestHandler):
def handle(self):
filename = self.rfile.readline().strip().decode('UTF-8')
print("local file server is getting '{}' for {}.".format(filename, self.client_address[0]))
with open("{}/{}".format(self.server.root_dir, filename), "rb") as f:
self.wfile.write(f.read())
self.wfile.close()
class TcpFileServer:
def __init__(self, root_dir='.'):
HOST, PORT = '', 0
self.server = socketserver.TCPServer((HOST, PORT), RequestHandler)
self.server.root_dir = root_dir
self.ip, self.port = self.server.server_address
def __enter__(self):
self.run()
return self
def run(self):
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.daemon = True
self.server_thread.start()
print("local file server is runing on {}:{}. root='{}'".format(self.ip, self.port, self.server.root_dir))
def __exit__(self, exc_type, exc_val, exc_tb):
self.server.shutdown()
self.server.server_close()
if __name__ == "__main__":
root_dir = '.' if len(sys.argv) <= 1 else sys.argv[1]
with TcpFileServer(root_dir):
while True:
time.sleep(10)