• socketserver网络编程简单的小例子


    1:网络编程之socketserver

    1:首先socketserver 服务器调用socketserver 模块

    2:继承了socketserver.BaseRequestHandler

    3:在父类的基础上重写了handle

    下面是一个简单的文件登录文件上传的例子

    server端

    import socketserver
    import json
    import struct
    import socket
    
    class MyTCPHandler(socketserver.BaseRequestHandler):
    
    
    def handle(self):
        flag = self.login_check()
        while flag:
            try:
                self.data = self.request.recv(1024).strip()
                print('{} wrote'.format(self.client_address[0]))
                print(self.data)
                self.request.send(self.data.upper())
                print(self.data.decode('utf-8'))
                if self.data.decode('utf-8') == '2':
                    self.uploading()
    
            except ConnectionResetError as e:
                print('error', e)
                break
    
    def login_check(self):
        dic_user = {
            'name': 'qwer',
            'pwad': '1234'
        }
        dic_clinet = self.request.recv(1024).strip()
        dic_clinet = json.loads(dic_clinet)
        print(dic_clinet)
        if dic_user['name'] == dic_clinet['name'] and 
                dic_user['pwad'] == dic_clinet['pwad']:
            self.request.send(b'True')
            return True
    
    def uploading(self):
        '''接受上传文件'''
        ret = self.request.recv(1024)
        dic_client = json.loads(ret)
        print(dic_client)
        self.request.send(b'Start To upload')
        print('Start the download')
        size = dic_client['size']
        with open(dic_client['filename'],'wb') as f:
            while size:
                ret = self.request.recv(1024)
                f.write(ret)
                size -= len(ret)
        print('下载完毕!')
    
    
    
    if __name__ == '__main__':
        Host, port = '127.0.0.1', 9999
        # sever = socketserver.TCPServer((Host, port), MyTCPHandler)
        sever = socketserver.ThreadingTCPServer((Host, port), MyTCPHandler)
        sever.serve_forever()
    

    client端

    import socket
    import json
    import os
    import sys
    import time
    
    #进度条
    import time
    from tqdm import tqdm
    
    # for i in tqdm(range(100)):
    #     time.sleep(0.05)
    
    def processBar(num, total):
    
        rate = num / total
        rate_num = int(rate * 100)
        if rate_num == 100:
            r = '
    %s>%d%%
    ' % ('|' * rate_num, rate_num,)
        else:
            r = '
    %s>%d%%' % ('|' * rate_num, rate_num,)
        sys.stdout.write(r)
        sys.stdout.flush
    
    
    class Client():
        '''客户端'''
        cmd_list = [
            ('下载文件', 'ncftpget'),
            ('上传文件', 'upload'),
            ('切换目录', 'chdir'),
            ('创建目录', 'create_directory'),
            ('删除文件或者目录','expurgate '),
        ]
        def __init__(self):
            self.client = socket.socket() #实例socket对象
        def connect(self, ip, port):
            '''绑定端口'''
            self.client.connect((ip, port))
        def logon(self):
            '''用户登录'''
            name = input('user_name:')
            pawd = input('passwork:')
            user_dic = {
                'name': name,
                'pwad': pawd
            }
            self.client.send(json.dumps(user_dic).encode('utf-8'))
            ret = self.client.recv(1024).decode('utf-8')
            print(ret)
            return ret
        def User_input(self):
            flag = self.logon()
            name_path = '/home/'
            while flag:
                for index, val in enumerate(self.cmd_list, 1):
                    print('%s  %s'%(index, val[0]))
                inp = input('%s:'%name_path)
                self.client.send(inp.encode('utf-8'))
                ret = self.client.recv(1024).decode('utf-8')
                if inp == '2':
                    self.upload()
    
            else:
                print('密码错误!')
    
        def ncftpget(self):
            '''下载文件'''
        def upload(self):
            '''上传文件'''
            path_name = r'G:python笔记Pythonjingday18video1 深圳校区 python fullstuck 1期 day18 内容回顾.mp4'
            size = os.path.getsize(path_name)
            print(size)
            total = size
            dic_user = {
                'means': 'uploading',
                'filename': 'test.mp4',
                'size': size,
            }
            self.client.send(json.dumps(dic_user).encode('utf-8'))
            ret = self.client.recv(1024)
            print(ret)
            with open(path_name, 'rb') as f:
                count = 0
                time_old = time.clock()
                pbar = tqdm(total=size)
                while size:
                    data = f.read(1024)
                    self.client.send(data)
                    size -= len(data)
                    count += len(data)
    
                    pbar.update(len(data)) #进度条
    
                    # processBar(count, total) #进度条
                time_new = time.clock()
                pbar.close()
                print('上传完毕!一个用时%s秒'%int(time_new - time_old))
    
    
        def chdir(self):
            '''切换目录'''
        def create_directory(self):
            '''创建目录'''
        def expurgate(self):
            '''删除文件或者文件夹'''
    
    if __name__ == '__main__':
        # Host, port = '127.0.0.1', 9999
        Host, port = '192.168.16.46', 9999
        cl = Client()
        cl.connect(Host, port)
        cl.User_input()
    
  • 相关阅读:
    null和undefined的区别
    "NetworkError: 404 Not Found fontawesome-webfont.woff?v=4.0.3
    php字符串
    php数组
    Oracle 和 MySQL的区别(不完整)
    拦截器和过滤器的区别
    SpringMVC和Struts2的区别
    Redis的介绍
    SpringBoot入门(2)
    SpringBoot入门(1)
  • 原文地址:https://www.cnblogs.com/leiwenxuan/p/9665310.html
Copyright © 2020-2023  润新知