加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
tcp_file_server.py 1.36 KB
一键复制 编辑 原始数据 按行查看 历史
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)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化