溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在python中使用socket傳輸圖片

發(fā)布時間:2021-03-24 15:41:37 來源:億速云 閱讀:477 作者:Leah 欄目:開發(fā)技術

怎么在python中使用socket傳輸圖片?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

服務器

LOCAL_IP = '192.168.100.22'  #本機在局域網(wǎng)中的地址,或者寫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協(xié)議
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #設置端口
  sock.bind((LOCAL_IP, PORT))    #綁定端口
  sock.listen(3)          #監(jiān)聽端口
  while True:
    sc,sc_name = sock.accept()  #當有請求到指定端口是 accpte()會返回一個新的socket和對方主機的(ip,port)
    print('收到{}請求'.format(sc_name))
    infor = sc.recv(1024)    #首先接收一段數(shù)據(jù),這段數(shù)據(jù)包含文件的長度和文件的名字,使用|分隔,具體規(guī)則可以在客戶端自己指定
    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('應該接收{(diào)},實際接收{(diào)}'.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,發(fā)送文件長度和文件名
    reply = sock.recv(1024)
    if 'ok' == reply.decode():       #確認一下服務器get到文件長度和文件名數(shù)據(jù)
      go = 0
      total = len(data)
      while go < total:            #發(fā)送文件
        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是以流的形式傳輸數(shù)據(jù),我們無法判斷開頭和結尾,簡單的方法是沒傳送一個文件,就使用一個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

看完上述內(nèi)容,你們掌握怎么在python中使用socket傳輸圖片的方法了嗎?如果還想學到更多技能或想了解更多相關內(nèi)容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI