socket 练习 ftp

server.py

__author__ = 'zhaobin022'


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import SocketServer
import subprocess
import re
import os

class MyServer(SocketServer.BaseRequestHandler):

    def handle(self):
        # print self.request,self.client_address,self.server
        conn = self.request
        conn.sendall('from %s%s ' % self.client_address )
        Flag = True
        while Flag:
            print 'in server loop'
            data = conn.recv(1024)
            print 'after server loop'
            if data == 'sendcommand':
                conn.sendall('ready')
                command = conn.recv(1024)
                p=subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                (stdoutput,erroutput) = p.communicate()
                print (stdoutput,erroutput)
                if len(erroutput) == 0:
                    total = len(stdoutput)
                    conn.sendall('total')
                    data = conn.recv(1024)
                    if data == 'ready':
                        conn.sendall(str(total))
                        data = conn.recv(1024)
                        if data == 'begin':
                            conn.sendall(stdoutput)

                else:
                    conn.sendall('error')
                    print 'send error'
                    data = conn.recv(1024)
                    if data == 'senderror':
                        print 'in senderror errouput'
                        conn.sendall(erroutput)
            elif data == 'sendfile':
                conn.sendall('ready')
                file_size = int(conn.recv(1024))
                received = 0
                conn.sendall('begin')
                count = 0
                with open('upload/1.jpg' , 'wb') as f:
                    while True:
                        count+=1
                        data = conn.recv(1024)
                        print len(data),'data len'
                        f.write(data)
                        received += len(data)
                        print received,'received'
                        if file_size <= received:
                            print 'finish upload'
                            conn.sendall('finish')
                            Flag = False
                            break
            elif data.startswith('get'):
                p = re.compile(r'get\s+(.+)')
                m = p.search(data)
                if m:
                    file_path = m.group(1)
                    if not os.path.exists(file_path):
                        print 'file not exist !!!!!'
                        conn.sendall('false | file not exist !!!!! ')
                        break
                    else:
                        file_size = os.path.getsize(file_path)
                        print 'before ture==='
                        conn.sendall('true | %d ' % file_size)
                        data = conn.recv(1024)
                        if data == 'begin':
                            with open(file_path,'rb') as f:
                                conn.sendall(f.read())

            elif data.startswith('put'):
                print 'in put..............'

                p = re.compile(r'put\s+(.+)')
                m = p.search(data)
                if m:
                    file_path = m.group(1)
                    file_list = file_path.split('/')
                    if len(file_list) == 2:
                        file_name = file_list[1]
                    else:
                        file_name = file_list[0]
                    conn.sendall('getsize')
                    file_size = int(conn.recv(1024))
                    received = 0
                    conn.sendall('begin')
                    with open('upload/%s' % file_name,'wb') as f:
                        while True:
                            data = conn.recv(1024)
                            f.write(data)
                            received+=len(data)
                            if received >= file_size:
                                conn.sendall('finish')
                                break
                else:
                    print 'Please input the right file path !'
                    continue

            elif data == 'exit':
                print 'in exit'
                break

if __name__ == '__main__':
    server = SocketServer.ThreadingTCPServer(('127.0.0.1',8010),MyServer)
    server.serve_forever()

ftpclient.py

__author__ = 'zhaobin022'
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import socket
import os
import re


ip_port = ('127.0.0.1',8010)
sk = socket.socket()
sk.connect(ip_port)
sk.settimeout(5)
data = sk.recv(1024)
print 'receive:',data

while True:
    command  = raw_input("->")
    if command.startswith('put '):
        p = re.compile(r'put\s+(.+)')
        m = p.search(command)
        if m:

            file_path = m.group(1)
            if not os.path.exists(file_path):
                print 'file not exist !!!!!'
                continue
            else:
                sk.sendall(command)
                data = sk.recv(1024)
                if data == 'getsize':
                    file_size = os.path.getsize(file_path)
                    sk.sendall(str(file_size))
                    data = sk.recv(1024)
                    if data == 'begin':
                        with open(file_path,'rb') as f:
                            sk.sendall(f.read())
                        data = sk.recv(1024)
                        if data == 'finish':
                            print 'upload ok !!!!!!!!!!'
                            continue

        else:
            print 'Please input the right file path !'
            continue

    elif command.startswith('get'):
        p = re.compile(r'get\s+(.+)')
        m = p.search(command)
        if m:
            sk.sendall(command)
            data = sk.recv(1024)
            Flag , msg = data.split('|')
            if Flag.strip() == 'false':
                print msg
                continue
            elif Flag.strip() == 'true':
                file_path = m.group(1)
                file_name = file_path.split('/')[1]
                file_size = int(msg)
                received = 0
                sk.sendall('begin')
                with open('download/%s' % file_name,'wb') as f:
                    while True:
                        data = sk.recv(1024)
                        f.write(data)
                        received += len(data)
                        if received >= file_size:
                            print 'get successfull !!!!!!!'
                            break
        else:
            print 'Please input the right get command !'
            continue
    elif command.strip() == 'exit':
        sk.sendall('exit')
        break

    else:
        print 'Please input the right command !'
        continue





sk.close()

 

posted on 2015-12-17 14:57  zhaobin022  阅读(148)  评论(0编辑  收藏  举报