python implementation using a socket file transfer pictures and video

This article describes the implementation of a file using python socket transfer pictures and video, the paper gives an example of the code, need friends can refer to
the need to develop some network communication applications often use a variety of network protocols communication, bloggers in the development of laboratory robots would face the need to collect the pictures on the robot back to the server for processing the identification, implementation in python as follows (only posted the key code)

Service-Terminal

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()

Client

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

to sum up

The above is a python small series to introduce the use of socket implementation transfer pictures and video files, we want to help
content on more than how many, and finally to recommend a good reputation in the number of public universities [programmers], there are a lot of old-timers learning

Skills, learning experience, interview skills, workplace experience and other share, the more carefully prepared the zero-based introductory information, information on actual projects,

The method has timed programmer Python explain everyday technology, to share some of the learning and the need to pay attention to small detailsHere Insert Picture Description

Published 64 original articles · won praise 13 · views 50000 +

Guess you like

Origin blog.csdn.net/chengxun02/article/details/105151193