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()

原文地址:https://www.cnblogs.com/Collin-pxy/p/13034229.html