socket_server 

客户端程序 

import socket, os, json


class Ftcplient(object):
    def __init__(self):
        
        """
        初始化一个socket
        """
        
        self.client = socket.socket()
    def client_connect(self, ip, port): 
        """
      实现端口的连接
        """
    
        
        self.client.connect((ip, port))
  

    def help(self):
        """
        帮助窗口
        """

        msg = {
            '''
            ls 
            pwd
            cd / 
            get filename
            put filename
            '''
        }
        print(msg)
    def interative(self):
        """
        用户交互程序
        """
        
        while True:
          cmd = input('>>').strip()
          if len(cmd) == 0 or not cmd:
            break

          action = cmd.split()[0]      #判断用户输入的动作
          if hasattr(self, 'cmd_' + action):  #如果动作存在调用内部程序,不存在启用帮助程序
            func = getattr(self, 'cmd_' + action)
            func(cmd)
          else:
              help()

    def cmd_load(self, *args):
        """
        上传文件程序

        """
        cmd_split = args[0]
        filename = cmd_split.split()[1]
        if os.path.isfile(filename):
            while True:

               size = os.stat(filename).st_size
               file_msg = {
                   'action':'load',
                   'filename' : filename,
                   'filesize' : size,
                   'overriden' : True
                       }
               self.client.send(json.dumps(file_msg).encode('utf-8'))
               f = open(filename, 'rb')
               self.client.recv(1024)
               for line in f :
                  self.client.send(line)

               else:
                  print('the file has send finish')
                  f.close()
                  break


ftp = Ftcplient()
ftp.client_connect('localhost', 5500)
ftp.interative()

服务器端程序 这里用的是socket_server

import socketserver, json


class MyTCPHandler(socketserver.BaseRequestHandler):  # 条件1,自己创建一个类
    def handle(self):  # 重写父类中的handle()
        """
        socketserver 主要的运行窗口

        """
        while True:

            self.data = self.request.recv(1024)
            if not self.data or len(self.data) == 0:
                break
            cmd = self.data.decode()
            cmd = json.loads(cmd)
            action = cmd['action']

            if hasattr(self, action):
                func = getattr(self, action)
                func(cmd)

    def load(self, *args):
        """
        用于文件的下载

        """

        load_split = args[0]
        filesize = load_split['filesize']
        filename = load_split['filename']
        self.request.send('ok'.encode('utf-8'))
        if len(filename.split('.')) > 0:  #判断输入的文件名是文件格式如1.txt
            f = open('new_'+ filename, 'wb')
            receive_size = 0
            while receive_size < filesize:
                receive_info = self.request.recv(1024)
                f.write(receive_info)
                receive_size += len(receive_info)

            #                print("{} wrote:".format(self.client_address[0]))



if __name__ == "__main__":
    HOST, PORT = "localhost", 5500
    # Create the server, binding to localhost on port 9999
    server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)  # 实例化ThreadingTCPServer,并传递(端口号+IP),和请求类名
    server.serve_forever()  # 关闭

 

posted on 2018-06-01 17:37  python我的最爱  阅读(245)  评论(0编辑  收藏  举报