Python--day32--ftp文件传输报错的原因

解决办法:把buffer改小

server.py

 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.py

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

 

posted @ 2019-01-22 17:28  莱茵河的雨季  阅读(583)  评论(3编辑  收藏  举报