1 #!/usr/bin/python 2 # _*_ coding:utf-8 _*_ 3 import socket 4 client = socket.socket() 5 client.connect(("localhost", 8600)) 6 f = open("f1.txt", "rb") 11 data = f.read() 12 client.sendall(bytes(data)) 13 print(len(data)) 14 # rev_data = str(client.recv(102400), encoding="utf-8") 15 # print(rev_data) 16 f.close() 17 client.close()
1 #!/usr/bin/python 2 # _*_ coding:utf-8 _*_ 3 import socket 4 import os 5 import sys 6 7 8 def view_bar(num, total): 9 # rate = float(num) / float(total) 10 rate = num / total 11 rate_num = int(rate * 100) 12 r = '\r%s%d%%' % ("+" * rate_num, rate_num) 13 sys.stdout.write(r) 14 sys.stdout.flush() 15 16 17 server = socket.socket() 18 server.bind(("localhost", 8600)) 19 server.listen(5) 20 f1 = open("f1.bak", "wb") # 注意这个不能写到循环里面 21 22 # -------- 23 print("waiting...") 24 conn, address = server.accept() 25 count = 0 26 while True: 27 rev_data = conn.recv(102400000) # 28 # print("coming already !") 29 f1.write(rev_data) 30 num = os.path.getsize("f1.bak") 31 total = os.path.getsize("f1.txt") 32 view_bar(num, total) 33 if os.path.getsize("f1.bak") == os.path.getsize("f1.txt"): 34 print("\ntransfer successfully !") 35 print("count:", count) 36 break 37 count = count + 1 38 server.close()
当传送的文件是大文件时,这个程序没有任何问题,进度条正常显示,从0%-100%。一旦传送的是小文件,就开始卡死,0%,然后无限循环,后来改进了服务端,代码如下
1 #!/usr/bin/python 2 # _*_ coding:utf-8 _*_ 3 import socket 4 import os 5 import sys 6 import time 7 8 9 def view_bar(num, total): 10 # rate = float(num) / float(total) 11 rate = num / total 12 rate_num = int(rate * 100) 13 r = '\r%s%d%%' % ("+" * rate_num, rate_num) 14 sys.stdout.write(r) 15 sys.stdout.flush() 16 17 server = socket.socket() 18 server.bind(("localhost", 8600)) 19 server.listen(5) 20 f1 = open("f1.bak", "wb") 21 print("waiting...") 22 conn, address = server.accept() 23 total = os.path.getsize("f1.txt") 24 25 count = 0 26 while True: 27 num = os.path.getsize("f1.bak") 28 rev_data = conn.recv(102400) 29 if total < 10240: 30 # print("head") 31 f1.write(rev_data) 32 view_bar(total, total) 33 print("\ntransfer successfully !") 34 break 35 else: 36 # print("end") 37 f1.write(rev_data) 38 view_bar(num, total) 39 if num == total: 40 print("\ntransfer successfully !") 41 print("count:", count) 42 break 43 count = count + 1 44 f1.close() 45 server.close()
这时,新问题又来了,到底每次客户端上传的文件,服务端能接收多大?貌似跟服务端的conn.recv(102400)没有任何关系,如何把if total < 10240 改为 if total < 1024000,又发现传上来的文件不完整,求大神给与指点!!!谢谢!!!
文件写入后 flush 一下
竟然完美实现了!!!赞!赞!赞!