怎么在python中使用socket傳輸圖片?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
服務器端
LOCAL_IP = '192.168.100.22' #本機在局域網中的地址,或者寫127.0.0.1
PORT = 2567 #指定一個端口
def server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket.AF_INET 指ipv4 socket.SOCK_STREAM 使用tcp協議
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #設置端口
sock.bind((LOCAL_IP, PORT)) #綁定端口
sock.listen(3) #監聽端口
while True:
sc,sc_name = sock.accept() #當有請求到指定端口是 accpte()會返回一個新的socket和對方主機的(ip,port)
print('收到{}請求'.format(sc_name))
infor = sc.recv(1024) #首先接收一段數據,這段數據包含文件的長度和文件的名字,使用|分隔,具體規則可以在客戶端自己指定
length,file_name = infor.decode().split('|')
if length and file_name:
newfile = open('image/'+str(random.randint(1,10000))+'.jpg','wb') #這里可以使用從客戶端解析出來的文件名
print('length {},filename {}'.format(length,file_name))
sc.send(b'ok') #表示收到文件長度和文件名
file = b''
total = int(length)
get = 0
while get < total: #接收文件
data = sc.recv(1024)
file += data
get = get + len(data)
print('應該接收{},實際接收{}'.format(length,len(file)))
if file:
print('acturally length:{}'.format(len(file)))
newfile.write(file[:])
newfile.close()
sc.send(b'copy') #告訴完整的收到文件了
sc.close()客戶端
address = ('192.168.100.22', 2567)
def send(photos):
for photo in photos[0]:
print('sending {}'.format(photo))
data = file_deal(photo)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(address)
sock.send('{}|{}'.format(len(data), file).encode()) #默認編碼 utf-8,發送文件長度和文件名
reply = sock.recv(1024)
if 'ok' == reply.decode(): #確認一下服務器get到文件長度和文件名數據
go = 0
total = len(data)
while go < total: #發送文件
data_to_send = data[go:go + 1024]
sock.send(data_to_send)
go += len(data_to_send)
reply = sock.recv(1024)
if 'copy' == reply.decode():
print('{} send successfully'.format(photo))
sock.close() #由于tcp是以流的形式傳輸數據,我們無法判斷開頭和結尾,簡單的方法是沒傳送一個文件,就使用一個socket,但是這樣是消耗計算機的資源,博主正在探索更好的方法,有機會交流一下
def file_deal(file_path): #讀取文件的方法
mes = b''
try:
file = open(file_path,'rb')
mes = file.read()
except:
print('error{}'.format(file_path))
else:
file.close()
return mes看完上述內容,你們掌握怎么在python中使用socket傳輸圖片的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。