服务 器端:
import SocketServer,commands,time
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
while 1:
self.data=self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
if not self.data:
print "client %s is dead!" %self.client_address[0]
break
user_input=self.data.split()
if user_input[0]=='get':
with open(user_input[1],'rb') as f:
self.request.sendall(f.read())
time.sleep(5)
self.request.send("ftpover")
continue
cmd_status,result=commands.getstatusoutput(self.data)
if len(result.strip())!=0:
self.request.sendall(result)
continue
else:
self.request.sendall('done')
if __name__=="__main__":
host,port='localhost',9999
server=SocketServer.ThreadingTCPServer((host,port),MyTCPHandler)
server.serve_forever()
客户端:
#coding:utf-8
import socket,time
host='localhost'
port=9999
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
while 1:
cmd=raw_input("your command:").strip()
if len(cmd)==0:continue
s.sendall(cmd)
if cmd.split()[0]=='get':
with open(cmd.split()[1],'wb') as f :
while 1:
data=s.recv(1024)
if data=='ftpover':break
if not data:break
f.write(data)
continue
else:
print s.recv(1024)
s.close()