zoukankan      html  css  js  c++  java
  • python_socket_tcp_文件传输

    server.py
    import json
    import struct
    import socket
    
    # 接收
    sk = socket.socket()
    # sk.bind(('127.0.0.1',9001))
    sk.bind(('192.168.31.159',9005))
    sk.listen()
    
    conn,_ =sk.accept()
    dic_len = struct.unpack('i',conn.recv(4))[0]  # 使用 struct.unpack()得到字典的长度
    msg = conn.recv(dic_len).decode('utf-8')      # 接受字典内容并decode成字符串
    msg = json.loads(msg)                         # 将json字符串loads为字典
    
    with open(msg['filename'],'wb') as f:
        while msg['filesize'] > 0:
            content = conn.recv(1024)
            msg['filesize'] -= len(content)
            f.write(content)
    conn.close()
    sk.close()
    
    client.py
    import os
    import json
    import struct
    import socket
    # 发送
    sk = socket.socket()
    # sk.connect(('192.168.14.109',9012))
    # sk.connect(('127.0.0.1',9001))
    sk.connect(('192.168.31.88',9005))
    
    # 文件名文件大小
    abs_path = r"C:Users12078Desktoppython学习笔记.pdf"
    filename = os.path.basename(abs_path)
    filesize = os.path.getsize(abs_path)
    dic = {'filename':filename,'filesize':filesize}
    str_dic = json.dumps(dic)
    b_dic = str_dic.encode('utf-8')
    
    sk.send(struct.pack('i',len(b_dic)))  # 先将字典的长度使用struct.pack()发给接收端
    sk.send(b_dic)                        # 再发送字典数据
    
    with open(abs_path,mode = 'rb') as f:
        while filesize>0:
            content = f.read(1024)
            filesize -= len(content)
            sk.send(content)
    sk.close()
    
    
  • 相关阅读:
    bzoj 3262: 陌上花开
    hdu 5618 Jam's problem again
    bzoj 1176: [Balkan2007]Mokia
    bzoj 2683: 简单题
    Codevs 1080 线段树练习(CDQ分治)
    bzoj 3223: Tyvj 1729 文艺平衡树
    bzoj 1503: [NOI2004]郁闷的出纳员
    bzoj 1208: [HNOI2004]宠物收养所
    bzoj 1588: [HNOI2002]营业额统计
    bzoj 3224: Tyvj 1728 普通平衡树
  • 原文地址:https://www.cnblogs.com/Collin-pxy/p/13034229.html
Copyright © 2011-2022 走看看