大文件上传

大文件上传

服务端

import socket
import os
import json
import struct

server = socket.socket()
server.bind(('127.0.0.1',8080))
server.listen(5)

while True:
    conn,addr = server.accept()
    while True:
        try:
            head=conn.recv(4)
            dic_len=struct.unpack('i',head)[0]

            b_json_dic=conn.recv(dic_len)
            dic=json.loads(b_json_dic.decode('utf-8'))

            file_len=dic.get('file_len')
            recv_len = 0 #已经接收到的数据长度
            with open(dic.get('file_name'),'wb')as f:
                while recv_len < file_len:
                    data = conn.recv(1024)
                    f.write(data)
                    recv_len+=len(data)#已接收的数据长度不停的增加,直到超过文件长度停止
                print('上传成功')
        except ConnectionResetError as e:
            print(e)
            break
    conn.close()

客户端

import json
import os
import socket
import struct

clicent = socket.socket()#拿起电话
clicent.connect(('127.0.0.1',8080))#,拨号

while True:
    MOVIE_DIR = r'C:UsersAdministratorDesktop新建文件夹'
    movie_list = os.listdir(MOVIE_DIR)

    for i,movie in enumerate(movie_list,1):
        print(i,movie)
    choice = input('shuru')
    if choice.isdigit():
        choice = int(choice)-1
        if choice in range(0,len(movie_list)):
            path = movie_list[choice]

            file_path = os.path.join(MOVIE_DIR,path)
            file_len = os.path.getsize(file_path)
            res_dic = {
                'file_name':'性感荷官在线发牌.mp4',
                'file_len':file_len,
                'msg':'注意身体,多喝营养快线'
            }
            json_d = json.dumps(res_dic)
            b_json_dic = json_d.encode('utf-8')

            header = struct.pack('i',len(b_json_dic))

            clicent.send(header)

            clicent.send(b_json_dic)
            with open(file_path,'rb') as f:
                for i in f:
                    clicent.send(i)
        else:
            print('not ')
    else:
        print('dssd')

原文地址:https://www.cnblogs.com/ZDQ1/p/11344404.html