• 解决沾包问题、并发 练习


    服务端

    import socketserver
    import struct
    import json

    class MyRequestHandle(socketserver.BaseRequestHandler):
    def handle(self):
    print(self.client_address)
    while True:
    try:
    cmd = self.request.recv(1024)

    if len(cmd) == 0: break
    print(cmd.decode('utf-8'))
    with open(cmd, mode='rb') as f:
    file = f.read()

    total_size = len(file)

    header_dic = {
    "total_size": total_size,
    "md5": "123123xi12ix12"
    }

    json_str = json.dumps(header_dic)
    json_str_bytes = json_str.encode('gbk')

    x = struct.pack('i', len(json_str_bytes))
    self.request.send(x)

    self.request.send(json_str_bytes)
    self.request.send(file)

    except Exception:
    break
    self.request.close()

    s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyRequestHandle)
    s.serve_forever()

    客户端

    import struct
    import json
    import os
    from socket import *

    client=socket(AF_INET,SOCK_STREAM)
    client.connect(('127.0.0.1',8080))

    while True:
    cmd=input('请输入需要下载的文件地址>>:').strip()
    if not os.path.exists(cmd):
    continue
    client.send(cmd.encode('utf-8'))
    x=client.recv(4)
    header_len=struct.unpack('i',x)[0]
    print(header_len)

    json_str_bytes=client.recv(header_len)
    json_str=json_str_bytes.decode('utf-8')
    header_dic=json.loads(json_str)
    print(header_dic)
    total_size=header_dic["total_size"]

    recv_size = 0
    while recv_size < total_size:
    recv_data=client.recv(1024)
    recv_size+=len(recv_data)
    file=recv_data
    choice=cmd.rsplit('.', 1)[1]
    if choice == 'jpg':
    with open(r'C:UsersdellDesktoppython14期day37代码下载文件复制.jpg',mode='ab')as f:
    f.write(file)
    continue
    elif choice == 'txt':
    with open(r'C:UsersdellDesktoppython14期day37代码下载文件作业.txt',mode='ab')as f:
    f.write(file)
    continue
    elif choice == 'mp4':
    with open(r'C:UsersdellDesktoppython14期day37代码下载文件复制.mp4',mode='ab')as f:
    f.write(file)
    continue
    else:
    print()
  • 相关阅读:
    Java内存管理的小技巧
    Java 数组
    cmd命令大全
    wget 使用技巧
    Excellent Eclipse Plugin
    A Tutorial on Clustering Algorithms
    KMeans 算法
    Windowtester Pro Automation test environment Setup using VM Ware Client by Remote Desktop Connection
    POP3、SMTP、IMAP、Exchange
    LeetCode Validate Binary Search Tree
  • 原文地址:https://www.cnblogs.com/0B0S/p/12746765.html
Copyright © 2020-2023  润新知