天天看點

上傳下載下傳作業(socket)

client

import os
import json
import socket

sk = socket.socket()
sk.connect(('127.0.0.1',8080))

def get_filename(file_path):
    filename = os.path.basename(file_path)
    return filename

#選擇 操作
operate = ['upload','download']
for num,opt in enumerate(operate,1):
    print(num,opt)
num = int(input('請輸入您要做的操作序号 : '))
if num == 1:
    '''上傳操作'''
    #file_path = 'E:\python10\day33\作業.py'
    file_path = input('請輸入要上傳的檔案路徑 : ')
    # 告訴對方要上傳的檔案的名字
    file_name = get_filename(file_path)
    # 讀要上傳的檔案 存成字元串
    with open(file_path,encoding='utf-8') as  f:
        content = f.read()
    dic = {'operate':'upload','filename':file_name,'content':content}
    # 将字元串send給server端
    str_dic = json.dumps(dic)
    sk.send(str_dic.encode('utf-8'))
    # server端接收 bytes轉碼程字元串
    # server端打開檔案 寫檔案
elif num == 2:
    '''下載下傳操作'''
sk.close()



server

import json
import socket

sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()

conn,addr = sk.accept()
content = conn.recv(1024).decode('utf-8')
content_dic = json.loads(content)
if content_dic['operate'] == 'upload':
    conn.send(b'received!')
    with open(content_dic['filename'],'wb') as f:
        while content_dic['filesize']:
            file = conn.recv(1024)
            f.write(file)
            content_dic['filesize'] -= len(file)
conn.close()
sk.close()


           
###server
import json
import struct
import socket

sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()

conn,addr = sk.accept()
dic_len = conn.recv(4)  # 4個位元組 數字的大小
dic_len = struct.unpack('i',dic_len)[0]
content = conn.recv(dic_len).decode('utf-8')  # 70
content_dic = json.loads(content)
if content_dic['operate'] == 'upload':
    with open(content_dic['filename'],'wb') as f:
        while content_dic['filesize']:
            file = conn.recv(1024)
            f.write(file)
            content_dic['filesize'] -= len(file)
conn.close()
sk.close()


##client
import os
import json
import struct
import socket

sk = socket.socket()
sk.connect(('127.0.0.1',8080))

def get_filename(file_path):
    filename = os.path.basename(file_path)
    return filename

#選擇 操作
operate = ['upload','download']
for num,opt in enumerate(operate,1):
    print(num,opt)
num = int(input('請輸入您要做的操作序号 : '))
if num == 1:
    '''上傳操作'''
    file_path = input('請輸入要上傳的檔案路徑 : ')
    file_size = os.path.getsize(file_path)  # 擷取檔案大小
    file_name = get_filename(file_path)
    dic = {'operate': 'upload', 'filename': file_name,'filesize':file_size}
    str_dic = json.dumps(dic).encode('utf-8')
    ret = struct.pack('i', len(str_dic))  # 将字典的大小轉換成一個定長(4)的bytes
    sk.send(ret + str_dic)
    with open(file_path,'rb') as  f:
        while file_size:
            content = f.read(1024)
            sk.send(content)
            file_size -= len(content)
elif num == 2:
    '''下載下傳操作'''
sk.close()
           

上傳檔案

#發送端 client
#coding=gbk
#發送端 client
import socket
import os
import json
import struct
sk=socket.socket()
sk.connect(('127.0.0.1',8080))
buffer=1024
# 發送檔案
head={'filename':'01 python fullstack s9day33 複習.mp4',
                 'filepath':r'E:\建立檔案夾\Python全棧9期(第一部分):基礎+子產品+面向對象+網絡程式設計\day33',
                'filesize':None}
file_path=os.path.join(head['filepath'],head['filename'])#計算檔案的絕對路徑
filesize=os.path.getsize(file_path)#計算檔案的大小
head['filesize']=filesize#把計算出的檔案大小指派給報頭
json_head=json.dumps(head)#字典轉換成字元串
bytes_head=json_head.encode('utf-8')#字元串轉換成bytes類型
# 計算head的長度
head_len=len(bytes_head)#報頭的長度
pack_len=struct.pack('i',head_len)#用struct.pack把報頭的長度轉換成固定格式的bytes類型
# print(pack_len)
sk.send(pack_len)#先發報頭的長度
sk.send(bytes_head)#再發送bytes類型的報頭
with open(file_path,'rb') as f:
    while filesize:
       # print(filesize)
       if  filesize>buffer:
           content=f.read(buffer)#每次讀出來的内容
           sk.send(content)
           filesize-=buffer
       else:
           content=f.read(filesize)
           sk.send(content)
           break
sk.close()



#server
#coding=gbk
#server
#實作大檔案下載下傳或上傳
import socket
import json
import struct
sk=socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()
conn,addr=sk.accept()
buffer=1024
#接收
head_len=conn.recv(4)#接受報頭的長度bytes類型
head_len=struct.unpack('i',head_len)[0]#unpack得到報頭的長度的數字
json_head=conn.recv(head_len).decode('utf-8')#接受bytes類型的報頭
head=json.loads(json_head)#将json格式轉換成字典
filesize=head['filesize']
with open(head['filename'],'wb') as f:
    while filesize:
        # print(filesize)
        if filesize>= buffer:
            content=conn.recv(buffer)#分次讀取并寫入檔案裡面
            f.write(content)
            filesize-=buffer
        else:
            content=conn.recv(filesize)#一次寫入檔案裡面
            f.write(content)
            break
conn.close()
sk.close()