這篇文章主要介紹了Python基于stuck實現scoket文件傳輸的方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
使用socket中的struck來實現客戶端發送
服務端:
客戶端:
# -*- coding: UTF-8 -*- import socket, time, socketserver, struct, os, _thread host = '127.0.0.1' port = 12307 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定義socket類型 s.bind((host, port)) # 綁定需要監聽的Ip和端口號,tuple格式 s.listen(1) def conn_thread(connection, address): while True: try: connection.settimeout(600) fileinfo_size = struct.calcsize('12sl')#12s表示12個字符,l表示一個長整型數 buf = connection.recv(fileinfo_size) if buf: # 如果不加這個if,第一個文件傳輸完成后會自動走到下一句,需要拿到文件大小信息才可以繼續執行 filename, filesize = struct.unpack('12sl', buf) filename_f = filename.decode("utf-8").strip('\00') # C語言中'\0'是一個ASCII碼為0的字符,在python中表示占一個位置得空字符 filenewname = os.path.join('e:\\', os.path.basename(filename_f)) print(u'文件名稱:%s , 文件大小: %s' % (filenewname, filesize)) recvd_size = 0 # 定義接收了的文件大小 file = open(filenewname, 'wb') print(u"開始傳輸文件內容") while not recvd_size == filesize: if filesize - recvd_size > 1024: rdata = connection.recv(1024) recvd_size += len(rdata) else: rdata = connection.recv(filesize - recvd_size) recvd_size = filesize file.write(rdata) file.close() print('receive done') # connection.close() except socket.timeout: connection.close() while True: print(u"開始進入監聽狀態") connection, address = s.accept() print('Connected by ', address) # thread = threading.Thread(target=conn_thread,args=(connection,address)) #使用threading也可以 # thread.start() _thread.start_new_thread(conn_thread, (connection, address)) s.close()
服務端效果:
# -*- coding: UTF-8 -*- import socket, os, struct s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 12307)) while True: filepath = input('請輸入要傳輸的文件絕對路徑:\r\n') print(type(filepath)) print(len(filepath.encode("utf-8"))) if os.path.isfile(filepath): #fileinfo_size = struct.calcsize('20sl') # 定義打包規則 # 定義文件頭信息,包含文件名和文件大小 fhead = struct.pack('12sl', filepath.encode("utf-8"), os.stat(filepath).st_size) print(os.stat(filepath).st_size) s.send(fhead) print (u'文件路徑: ', filepath) # with open(filepath,'rb') as fo: 這樣發送文件有問題,發送完成后還會發一些東西過去 fo = open(filepath, 'rb') while True: filedata = fo.read(1024) if not filedata: break s.send(filedata) fo.close() print (u'傳輸成功') # s.close()
客戶端效果
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Python基于stuck實現scoket文件傳輸的方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。