Python--day32--ftp文件傳輸報錯的緣由

解決辦法:把buffer改小json

server.pysocket

 1 #實現一個大文件的上傳或下載
 2 #配置文件 ip地址 端口號
 3 import json  4 import socket  5 import struct  6 sk = socket.socket()  7 #起服務
 8 sk.bind(('127.0.0.1', 8090))  9 sk.listen() 10 buffer = 1024
11 conn,addr = sk.accept() 12 #接收
13 head_len = conn.recv(4) 14 head_len = struct.unpack('i', head_len)[0] 15 json_head = conn.recv(head_len).decode('utf-8') 16 head = json.loads(json_head) 17 filesize = head['filesize'] 18 with open(head['filename'], 'wb') as f: 19     while filesize: 20         print(filesize) 21         if filesize >= buffer: 22             content = conn.recv(buffer) 23  f.write(content) 24             filesize -= buffer 25         else: 26             content = conn.recv(filesize) 27  f.write(content) 28             break
29 conn.close() 30 sk.close()

client.pyspa

 1 #發送端
 2 import os  3 import json  4 import struct  5 import socket  6 sk = socket.socket()  7 sk.connect(('127.0.0.1', 8090))  8 buffer = 1024
 9 
10 #發送文件
11 head = {'filepath':r'C:\Users\Administrator\Desktop', 12         'filename':r'test.txt', 13         'filesize':None} 14 fie_path = os.path.join(head['filepath'],head['filename']) 15 filesize = os.path.getsize(os.path.join(head['filepath'],head['filename'])) 16 
17 head['filesize'] = filesize 18 json_head = json.dumps(head)   #字典轉成了字符串
19 bytes_head = json_head.encode('utf-8')       #字符串轉bytes
20 print(json_head) 21 print(bytes_head) 22 #計算head的長度
23 head_len = len(bytes_head)  #報頭的長度
24 pack_len = struct.pack('i', head_len) 25 sk.send(pack_len)   #先發報頭的長度
26 sk.send(bytes_head) #再發送bytes類型的報頭
27 with open(fie_path, 'rb') as f: 28     while filesize: 29         print(filesize) 30         if filesize >= buffer: 31             content = f.read(buffer) #每次讀出來的內容
32  sk.send(content) 33             filesize -= buffer 34         else: 35             content = f.read(filesize) 36  sk.send(content) 37             break
38 sk.close()
相關文章
相關標籤/搜索