python:socket傳輸大檔案樣本,
檔案可以傳輸,但是對比傳輸前後的檔案:socket_test.txt,末尾有一些不一致服務端代碼:
#!/usr/bin/python# -*- coding: utf-8 -*-import sysreload(sys)sys.setdefaultencoding("utf-8")import time'''等待串連等待傳送檔案讀取資料寫入檔案並且儲存等待串連'''import socketimport threadingimport timeimport structdef function(newsock, address): FILEINFO_SIZE = struct.calcsize('128sI') '''定義檔案資訊(包含檔案名稱和檔案大小)大小。128s代表128個char[](檔案名稱),I代表一個integer or long(檔案大小)''' while 1: try: fhead = newsock.recv(FILEINFO_SIZE) filename, filesize = struct.unpack('128sI', fhead) '''把接收到的資料庫進行解包,按照打包規則128sI''' print "address is: ", address print filename, len(filename), type(filename) print filesize #filename = 'new_'+filename.strip('\00') # 命名新檔案new_傳送的檔案 filename = filename.strip('\00') fp = open(filename, 'wb') # 建立檔案,並且準備寫入 restsize = filesize print "recving..." while 1: if restsize > 102400: # 如果剩餘資料包大於1024,就去1024的資料包 filedata = newsock.recv(10240) else: filedata = newsock.recv(restsize) fp.write(filedata) #break if not filedata: break fp.write(filedata) restsize = restsize - len(filedata) # 計算剩餘資料包大小 if restsize <= 0: break fp.close() print "recv succeeded !!File named:", filename except Exception, e: print unicode(e).encode('gbk') print "the socket partner maybe closed" newsock.close() breaksock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立tcp串連sock.bind(('10.240.146.82', 8887)) # 定於連接埠和ipsock.listen(5) # 監聽while True: newsock, address = sock.accept() print "accept another connection" tmpThread = threading.Thread(target=function, args=(newsock, address)) # 如果接收到檔案,建立線程 tmpThread.start() # 執行線程print 'end'
用戶端代碼:
#!/usr/bin/python# -*- coding: utf-8 -*-import sysreload(sys)sys.setdefaultencoding("utf-8")'''輸入檔案名稱,並且上傳'''import socketimport timeimport structimport osf = open('socket_test.txt', 'wb')for i in range(1000000): f.write('for socket test, the line number is : ' + str(i) + '\n')f.close()sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.settimeout(50)e = 0try: sock.connect(('10.240.146.82', 8887)) print 'connect...'except socket.timeout, e: print 'timeout', eexcept socket.error, e: print 'error', eexcept e: print 'any', eif not e: #while (1): #filename = raw_input('input your filename------->') # 輸入檔案名稱 filename = 'socket_test.txt' FILEINFO_SIZE = struct.calcsize('128sI') # 編碼格式大小 fhead = struct.pack('128sI', filename, os.stat(filename).st_size) # 按照規則進行打包 sock.send(fhead) # 傳送檔案基本資料資料 fp = open(filename, 'rb') fp2 = open('local_test.txt','wb') i = 0 while 1: # 傳送檔案 filedata = fp.read(10240) if not filedata: break sock.sendall(filedata) fp2.write(filedata) print i i = i + 1 print "sending over..." fp.close() fp2.close()
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。