zoukankan      html  css  js  c++  java
  • 网编小练习来喽~~~

    1. 多用户同时登陆
      用户登陆,加密认证
      3. 上传/下载文件,保证文件一致性
      传输过程中现实进度条
      5. 不同用户家目录不同,且只能访问自己的家目录
    服务端
    import socketserver
    import struct
    import json
    import os
    import hashlib
    class MyServer(socketserver.BaseRequestHandler):
        def login(self):   # 登录
            u,p = self.request.recv(1024).decode('utf-8').split('|')
            with open('user pwd',mode='r',encoding= 'utf-8') as f:
                for line in f:
                    user,pwd = line.strip().split('|')
                    if u == user and p == pwd:
                        self.request.send('登录成功'.encode('utf-8'))
                        return True
                self.request.send('登录失败'.encode('utf-8'))
                return False
        def register(self):  # 注册
            u_name,p_word = self.request.recv(1024).decode('utf-8').split('|')
            md5 = hashlib.md5()
            md5.update(p_word)
            md5_word = md5.hexdigest()
            with open('user pwd',mode='r',encoding='utf-8') as f:
                for line in f:
                    user,pwd = line.strip().split('|')
                    if u_name == user:
                        self.request.send('注册失败'.encode('utf-8'))
                        return False
            with open('user pwd',mode= 'a',encoding='utf-8') as f:
                f.write(f'{u_name}|{md5_word}
    ')
                self.request.send('注册成功'.encode('utf-8'))
                return True
        def upload(self):  # 上传文件
            four_bytes = self.request.recv(4)
            dic_len = struct.unpack('i',four_bytes)[0]
            dic_bytes = self.request.recv(dic_len).decode('utf-8')
            dic = json.loads(dic_bytes)
            print(dic)
            with open(os.path.join(os.path.dirname('上传文件'),dic['file_name']),mode='wb') as f:
                total_size = 0
                md5 = hashlib.md5()
                while total_size < dic['file_size']:
                    every_data = self.request.recv(1024)
                    if every_data:
                        md5.update(every_data)
                        f.write(every_data)
                        total_size += len(every_data)
                    else:
                        break
                if md5.hexdigest() == dic['file_md5']:
                    self.request.send('上传成功'.encode('utf-8'))
                else:
                    self.request.send('上传失败'.encode('utf-8'))
                    os.remove(os.path.join(os.path.dirname('上传文件'),dic['file_name']))
        def download(self):  # 下载文件
            directory = os.listdir(os.path.dirname(__file__))
            s = ''
            for n,file_name in enumerate(directory ,1):
                s += f'序号:{n}	文件名{file_name}
    '
            dir_name = f'文件如下:
    {s}'
            self.request.send(dir_name.encode('utf-8'))
            choice = self.request.recv(1024).decode('utf-8')
            md5 = hashlib.md5()
            with open(os.path.join(os.path.dirname(__file__),directory[int(choice) - 1]), mode='rb') as f:
                while 1:
                    data = f.read(1024)
                    if data:
                        md5.update(data)
                    else:
                        break
            dic = {'file_name':directory[int(choice)-1],
                   'file_size':os.path.getsize(os.path.join(os.path.dirname(__file__),directory[int(choice) - 1])),
                   'file_md5':md5.hexdigest()}
            dic_json = json.dumps(dic)
            dic_json_bytes = dic_json.encode('utf-8')
            dic_len = len(dic_json_bytes)
            four_bytes = struct.pack('i',dic_len)
            self.request.send(four_bytes)
            self.request.send(dic_json_bytes)
            with open(os.path.join(os.path.dirname(__file__), directory[int(choice) - 1]), mode='rb')as f:
                while 1:
                    data = f.read(1024)
                    if data:
                        self.request.send(data)
                    else:
                        break
    
        def handle(self):
            choice = self.request.recv(1024).decode('utf-8')
            if choice == '1':
                ret = self.login()
                if ret:
                    while 1:
                        choice = self.request.recv (1024).decode('utf-8')
                        if choice == '1':
                            self.upload()
                        elif choice == '2':
                            self.download()
            elif choice :
                ret = self.register()
                if ret:
                    while 1:
                        choice = self.request.recv (1024).decode('utf-8')
                        if choice == '1':
                            self.upload()
                        elif choice == '2':
                            self.download()
    if __name__ == '__main__':
        ip_port = ('192.168.137.39',9999)
        socketserver.TCPServer.allow_reuse_address = True;
        server = socketserver.ThreadingTCPServer(ip_port,MyServer)
        server.serve_forever()
    
    客户端
    import socket
    import hashlib
    import os
    import struct
    import json
    client = socket.socket()
    client.connect(('192.168.137.39',9999))
    def login():  # 登录
        user = input('用户名').strip()
        pd = input('密码').strip()
        md5 = hashlib.md5()
        md5.update(pd.encode('utf-8'))
        pwd = md5.hexdigest()
        client.send(f'{user}|{pwd}'.encode('utf-8'))
        f_s = client.recv(1024).decode('utf-8')
        if f_s == '登录成功':
            print('登录成功')
            return  True
        else:
            print('登录失败')
            return False
    def register():  # 注册
        user = input('用户名').strip()
        p_word = input('密码').strip()
        md5 = hashlib.md5()
        md5.update(p_word.encode('utf-8'))
        pwd = md5.hexdigest()
        client.send(f'{user}|{pwd}'.encode('utf-'))
        result = client.recv(1024).decode('utf-8')
        if result == '注册成功':
            print(result)
            return True
        else:
            print(result)
            return False
    def upload():   # 上传文件
            path = input('请输入路径').strip()
            md5 = hashlib.md5()
            with open(path,mode='rb') as f:
                while 1:
                    data = f.read(1024)
                    if data:
                        md5.update(data)
                    else:
                        break
            dic = {'file_name':os.path.basename(path),
                   'file_size':os.path.getsize(path),
                   'file_md5': md5.hexdigest()}
            dic_json = json.dumps(dic)
            dic_json_bytes = dic_json.encode('utf-8')
            dic_len = len(dic_json_bytes)
            four_bytes = struct.pack('i',dic_len)
            client.send(four_bytes)
            client.send(dic_json_bytes )
            with open(path,mode='rb') as f:
                while 1:
                    data = f.read(1024)
                    if data:
                        client.send(data)
                    else:
                        break
            print(client.recv(1024).decode('utf-8'))
    
    def download():   # 下载文件
        dir_name = client.recv(1024).decode('utf-8')
        print(dir_name)
        choice = input('请输入你的选择').strip()
        client.send(choice.encode('utf-8'))
        four_bytes = client.recv(4)
        dic_len = struct.unpack('i',four_bytes)[0]
        dic_bytes = client.recv(dic_len).decode('utf-8')
        dic = json.loads(dic_bytes)
        print(dic)
        with open(os.path.join(os.path.dirname(__file__),'下载',dic['file_name']),mode='wb') as f:
            total_size = 0
            md5 = hashlib.md5()
            while total_size < dic['file_size']:
                every_data = client.recv(1024)
                if every_data:
                    md5.update(every_data)
                    f.write(every_data)
                    total_size += len(every_data)
                else:
                    break
            if md5.hexdigest() == dic['file_md5']:
                print('下载成功')
            else:
                print('下载失败')
                os.remove(os.path.join(os.path.dirname(__file__),dic['file_name']))
    
    choice = input('请选择:
    1:登录  2:注册').strip()
    client.send(choice.encode('utf-8'))
    if choice == '1':
        ret = login()
        if ret:
            while 1:
                choice =  input('请选择:
    1:上传文件  2:下载文件')
                client.send(choice.encode('utf-8'))
                if choice == '1':
                    upload()
                elif choice == '2':
                    download()
    elif choice == '2':
        ret = register()
        if ret:
            while 1:
                choice =  input('请选择:
    1:上传文件  2:下载文件')
                client.send(choice.encode('utf-8'))
                if choice == '1':
                    upload()
                elif choice == '2':
                    download()
    
    client.close()
    
  • 相关阅读:
    linux 和unix 的区别
    Ubuntu 12.04下安装ibus中文输入法
    安装vmware tools失败解决方法
    snort简介以及在Ubuntu下的安装
    ubuntu下tcpdump使用
    securecrt在linux与windows之间传输文件(转)
    大数据处理时用到maven的repository
    Spark之命令
    Spark之集群搭建
    Spark之scala
  • 原文地址:https://www.cnblogs.com/maqian/p/11977422.html
Copyright © 2011-2022 走看看