成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python基于stuck實(shí)現(xiàn)scoket文件傳輸

瀏覽:5日期:2022-07-31 10:28:02

使用socket中的struck來(lái)實(shí)現(xiàn)客戶端發(fā)送

服務(wù)端:

客戶端:

# -*- coding: UTF-8 -*-import socket, time, socketserver, struct, os, _thread host = ’127.0.0.1’port = 12307s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定義socket類型s.bind((host, port)) # 綁定需要監(jiān)聽(tīng)的Ip和端口號(hào),tuple格式s.listen(1) def conn_thread(connection, address): while True: try: connection.settimeout(600) fileinfo_size = struct.calcsize(’12sl’)#12s表示12個(gè)字符,l表示一個(gè)長(zhǎng)整型數(shù) buf = connection.recv(fileinfo_size) if buf: # 如果不加這個(gè)if,第一個(gè)文件傳輸完成后會(huì)自動(dòng)走到下一句,需要拿到文件大小信息才可以繼續(xù)執(zhí)行filename, filesize = struct.unpack(’12sl’, buf)filename_f = filename.decode('utf-8').strip(’00’) # C語(yǔ)言中’0’是一個(gè)ASCII碼為0的字符,在python中表示占一個(gè)位置得空字符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'開(kāi)始傳輸文件內(nèi)容')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'開(kāi)始進(jìn)入監(jiān)聽(tīng)狀態(tài)') 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()

服務(wù)端效果:

# -*- 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(’請(qǐng)輸入要傳輸?shù)奈募^對(duì)路徑:rn’) print(type(filepath)) print(len(filepath.encode('utf-8'))) if os.path.isfile(filepath): #fileinfo_size = struct.calcsize(’20sl’) # 定義打包規(guī)則 # 定義文件頭信息,包含文件名和文件大小 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: 這樣發(fā)送文件有問(wèn)題,發(fā)送完成后還會(huì)發(fā)一些東西過(guò)去 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實(shí)現(xiàn)scoket文件傳輸

客戶端效果

Python基于stuck實(shí)現(xiàn)scoket文件傳輸

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章: