Python Socket传输文件示例

yipeiwu_com5年前Python基础

发送端可以不停的发送新文件,接收端可以不停的接收新文件。

例如:发送端输入:e:\visio.rar,接收端会默认保存为 e:\new_visio.rar,支持多并发,具体实现如下;

接收端:

方法一:

#-*- coding: UTF-8 -*-
import socket,time,SocketServer,struct,os,thread
host='192.168.50.74'
port=12307
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #定义socket类型
s.bind((host,port)) #绑定需要监听的Ip和端口号,tuple格式
s.listen(1)

 
def conn_thread(connection,address): 
  while True:
    try:
      connection.settimeout(600)
      fileinfo_size=struct.calcsize('128sl') 
      buf = connection.recv(fileinfo_size)
      if buf: #如果不加这个if,第一个文件传输完成后会自动走到下一句
        filename,filesize =struct.unpack('128sl',buf) 
        filename_f = filename.strip('\00')
        filenewname = os.path.join('e:\\',('new_'+ filename_f))
        print 'file new name is %s, filesize is %s' %(filenewname,filesize)
        recvd_size = 0 #定义接收了的文件大小
        file = open(filenewname,'wb')
        print 'stat receiving...'
        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:
  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()

方法二:

#-*- coding: UTF-8 -*-
import socket,time,SocketServer,struct,os
host='192.168.50.74'
port=12307
ADDR=(host,port)

class MyRequestHandler(SocketServer.BaseRequestHandler):  
  def handle(self):   
    print('connected from:', self.client_address)
    while True:
      fileinfo_size=struct.calcsize('128sl') #定义文件信息。128s表示文件名为128bytes长,l表示一个int或log文件类型,在此为文件大小
      self.buf = self.request.recv(fileinfo_size)
      if self.buf: #如果不加这个if,第一个文件传输完成后会自动走到下一句
        self.filename,self.filesize =struct.unpack('128sl',self.buf) #根据128sl解包文件信息,与client端的打包规则相同
        print 'filesize is: ',self.filesize,'filename size is: ',len(self.filename) #文件名长度为128,大于文件名实际长度
        self.filenewname = os.path.join('e:\\',('new_'+ self.filename).strip('\00')) #使用strip()删除打包时附加的多余空字符
        print self.filenewname,type(self.filenewname)
        recvd_size = 0 #定义接收了的文件大小
        file = open(self.filenewname,'wb')
        print 'stat receiving...'
        while not recvd_size == self.filesize:
          if self.filesize - recvd_size > 1024:
            rdata = self.request.recv(1024)
            recvd_size += len(rdata)
          else:
            rdata = self.request.recv(self.filesize - recvd_size) 
            recvd_size = self.filesize
          file.write(rdata)
        file.close()
        print 'receive done'
    #self.request.close()

tcpServ = SocketServer.ThreadingTCPServer(ADDR, MyRequestHandler) 
print('waiting for connection...' )
tcpServ.serve_forever()

发送端:

#-*- coding: UTF-8 -*-
import socket,os,struct
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('192.168.50.74',12307))
while True:
  
  filepath = raw_input('Please Enter chars:\r\n')
  if os.path.isfile(filepath):
    fileinfo_size=struct.calcsize('128sl') #定义打包规则
    #定义文件头信息,包含文件名和文件大小
    fhead = struct.pack('128sl',os.path.basename(filepath),os.stat(filepath).st_size)
    s.send(fhead) 
    print 'client filepath: ',filepath
    # with open(filepath,'rb') as fo: 这样发送文件有问题,发送完成后还会发一些东西过去
    fo = open(filepath,'rb')
    while True:
      filedata = fo.read(1024)
      if not filedata:
        break
      s.send(filedata)
    fo.close()
    print 'send over...'
    #s.close()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python入门篇之对象类型

Python入门篇之对象类型

Python使用对象模型来存储数据。构造任何类型的值都是一个对象 所有的Python对象都拥有三个特性:身份、类型、值 身份: 每一个对象都有一个唯一的身份来标志自己,任何对象的身份可以...

django与小程序实现登录验证功能的示例代码

之前用小程序做项目,因为后台使用的java开发,一切顺利,但切换成django做RESTful API接口时,在登陆注册时一直出现问题,网上搜索,借助一个网友的回答,找到了一种可行的解决...

python 随机数生成的代码的详细分析

以下的文章主要是以介绍python随机数生成的代码来介绍Python随机数生成在实际操作过程中的具体应用,如果你对其的相关内容感兴趣的话,你就可以点击以下的文章。希望你会对它有所收获。...

Python切片工具pillow用法示例

本文实例讲述了Python切片工具pillow用法。分享给大家供大家参考,具体如下: 切片:使用切片将源图像分成许多的功能区域 因为要对图片进行切片裁剪,所以用到切片工具必不可少,在ub...

python基于K-means聚类算法的图像分割

python基于K-means聚类算法的图像分割

1 K-means算法 实际上,无论是从算法思想,还是具体实现上,K-means算法是一种很简单的算法。它属于无监督分类,通过按照一定的方式度量样本之间的相似度,通过迭代更新聚类中心,...