使用 SocketServer 實現 FTP Server
阿新 • • 發佈:2018-01-06
input ase server exists handler req class ont run
使用 SocketServer 實現 FTP Server ,以便讓多個客戶端進行上傳下載
[root@localhost ~]# 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()
[root@localhost ~]# 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()
使用 SocketServer 實現 FTP Server