Python基于stuck實現(xiàn)scoket文件傳輸
更新時間:2020年04月02日 15:20:44 作者:做夢的人-
這篇文章主要介紹了Python基于stuck實現(xiàn)scoket文件傳輸,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
使用socket中的struck來實現(xiàn)客戶端發(fā)送
服務(wù)端:
客戶端:
# -*- 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)) # 綁定需要監(jiān)聽的Ip和端口號,tuple格式
s.listen(1)
def conn_thread(connection, address):
while True:
try:
connection.settimeout(600)
fileinfo_size = struct.calcsize('12sl')#12s表示12個字符,l表示一個長整型數(shù)
buf = connection.recv(fileinfo_size)
if buf: # 如果不加這個if,第一個文件傳輸完成后會自動走到下一句,需要拿到文件大小信息才可以繼續(xù)執(zhí)行
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"開始傳輸文件內(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"開始進入監(jiān)聽狀態(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('請輸入要傳輸?shù)奈募^對路徑:\r\n')
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ā)送文件有問題,發(fā)送完成后還會發(fā)一些東西過去
fo = open(filepath, 'rb')
while True:
filedata = fo.read(1024)
if not filedata:
break
s.send(filedata)
fo.close()
print (u'傳輸成功')
# s.close()

客戶端效果

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pyqt 實現(xiàn)為長內(nèi)容添加滑輪 scrollArea
今天小編就為大家分享一篇pyqt 實現(xiàn)為長內(nèi)容添加滑輪 scrollArea,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
python判斷一個變量是否已經(jīng)設(shè)置的方法
這篇文章主要介紹了python判斷一個變量是否已經(jīng)設(shè)置的方法,有需要的朋友們可以跟著學習參考下。2020-08-08
Python實現(xiàn)快速排序算法及去重的快速排序的簡單示例
quick sort快速排序是一種再基礎(chǔ)不過的排序算法,使用Python代碼寫起來相當簡潔,這里我們就來看一下Python實現(xiàn)快速排序算法及去重的快速排序的簡單示例:2016-06-06
使用Python實現(xiàn)全攝像頭拍照與鍵盤輸入監(jiān)聽功能
這篇文章主要介紹了使用Python實現(xiàn)全攝像頭拍照與鍵盤輸入監(jiān)聽功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08

