使用 SocketServer 实现 FTP Server ,以便让多个客户端进行上传下载
[[email protected] ~]# cat ftp_server.py
#!/usr/bin/env python
#!-*- coding:utf-8 -*-
import threading import SocketServer class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): while True: self.cmd = self.request.recv(1024).strip() self.cmd_list = self.cmd.split() if self.cmd_list: if self.cmd_list[0] == ‘get‘: with open(self.cmd_list[1]) as fd: while True: self.data = fd.read(1024) self.request.sendall(self.data) if not self.data: self.request.sendall(‘EOF‘) break if not self.cmd: break class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass if __name__ == "__main__": HOST = "" PORT = 1234 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print "Server loop running in thread:", server_thread.name server.serve_forever()
[[email protected] ~]# cat ftp_client.py
#!/usr/bin/env python
#!-*- coding:utf-8 -*-
import os import tab import time import socket HOST = ‘192.168.1.16‘ PORT = 1234 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while True: cmd = raw_input("Please input cmd: ").strip() if cmd.lower()== ‘exit‘ or cmd.lower() == ‘quit‘: break cmd_list = cmd.split() if len(cmd_list) != 3: print "Ex: get file1 file2" continue else: s.sendall(cmd) if not os.path.exists(cmd_list[2]): dst_file = cmd_list[2] else: dst_file = cmd_list[2]+‘.new‘ n = 1 while True: data_rev = s.recv(1024) if data_rev.endswith(‘EOF‘): data = data_rev[:-3] else: data = data_rev if n == 1: with open(dst_file, ‘wb‘) as fd: fd.write(data) print data else: with open(dst_file, ‘a‘) as fd: fd.write(data) print data n += 1 if data_rev[-3:] == ‘EOF‘: print "destination file is %s" % dst_file break s.close()