【无标题】

SOCKET文件传输client

import socket
import struct
import json
from pathlib import Path
#定义路径全局变量,这里为客户端下载文件到本地的保存路径
#Download_dir = r'F:\quan\local_demo\local'
share_dir = Path('local')

def get_file(phone, send_data):
    # 给服务端发送命令
    phone.send(send_data.encode('utf-8'))
    print('request send')
    # 接收服务端数据

    # 1.先收报头长度
    print('A')
    obj = phone.recv(4)
    try:
        header_size = struct.unpack('i', obj)[0]
        # 2.收报头
        '''
                header_dic = {
                'filename': filename,
                'file_size': os.path.getsize(filename)
            }
        '''
        header_bytes = phone.recv(header_size)
        # 3.从报头中解析出数据的真实信息(报头字典)
        header_json = header_bytes.decode('utf-8')
        header_dic = json.loads(header_json)
        # 4.解析命令
        total_size = header_dic['file_size']
        filename = header_dic['filename']

        # 4.接受真实数据
        with open('%s/%s' % (share_dir, filename), 'wb') as f:
            recv_size = 0
            while recv_size < total_size:
                line = phone.recv(1024)
                f.write(line)
                recv_size += len(line)
                print('总大小:%s     已下载:%s' % (total_size, recv_size))
        print('download finished')
    except Exception as e:
        print(e)


def send_file(phone, send_data, cmd):
    # 给服务端发送命令
    phone.send(send_data.encode('utf-8'))
    print('request send')
    # 以读的方式打开文件,提取文件内容发送给客户端
    # 1.制作固定长度的报头
    filename = cmd[1]
    header_dic = {
        'filename': filename,
        'file_size': (share_dir / filename).stat().st_size
    }
    header_json = json.dumps(header_dic)  # 序列化为byte字节流类型
    header_bytes = header_json.encode('utf-8')  # 编码为utf-8(Mac系统)
    # 2.先发送报头的长度
    # 2.1 将byte类型的长度打包成4位int
    phone.send(struct.pack('i', len(header_bytes)))
    # 2.2 再发报头
    phone.send(header_bytes)
    # 2.3 再发真实数据
    with open((share_dir / filename), 'rb') as f:
        for line in f:
            phone.send(line)
    print("send finished")


def main():
    # 创建套接字
    phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 连接
    phone.connect(('xxx.xx.xx.xxx', 443))
    while True:
        inp = input('>>> ')
        send_data = inp.strip()
        cmd = inp.split()
        print(cmd[0])
        if not cmd:
            print('pass')
            continue
        if cmd[0] == 'quit':
            break
        if cmd[0] == 'get':
            get_file(phone, send_data)
        if cmd[0] == 'send':
            send_file(phone, send_data, cmd)
        print('nothing')
    # 关闭套接字
    phone.close()


if __name__ == '__main__':
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值