Python Socket传输文件示例


Posted in Python onJanuary 16, 2017

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

例如:发送端输入: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字典操作简明总结
Apr 13 Python
在Python的Django框架中获取单个对象数据的简单方法
Jul 17 Python
Python实现PS图像明亮度调整效果示例
Jan 23 Python
Python爬虫设置代理IP的方法(爬虫技巧)
Mar 04 Python
Python实现识别图片内容的方法分析
Jul 11 Python
Python中应该使用%还是format来格式化字符串
Sep 25 Python
Django model序列化为json的方法示例
Oct 16 Python
利用python实现简易版的贪吃蛇游戏(面向python小白)
Dec 30 Python
Python读取文件内容为字符串的方法(多种方法详解)
Mar 04 Python
使用anaconda安装pytorch的实现步骤
Sep 03 Python
Python利用Pillow(PIL)库实现验证码图片的全过程
Oct 04 Python
pytorch 实现变分自动编码器的操作
May 24 Python
python批量添加zabbix Screens的两个脚本分享
Jan 16 #Python
python一键升级所有pip package的方法
Jan 16 #Python
centos6.7安装python2.7.11的具体方法
Jan 16 #Python
python subprocess 杀掉全部派生的子进程方法
Jan 16 #Python
用python记录运行pid,并在需要时kill掉它们的实例
Jan 16 #Python
python 根据pid杀死相应进程的方法
Jan 16 #Python
总结python实现父类调用两种方法的不同
Jan 15 #Python
You might like
基于php验证码函数的使用示例
2013/05/03 PHP
php常用的安全过滤函数集锦
2014/10/09 PHP
ThinkPHP实现非标准名称数据表快速创建模型的方法
2014/11/29 PHP
phpmailer简单发送邮件的方法(附phpmailer源码下载)
2016/06/13 PHP
PHPStorm 2020.1 调试 Nodejs的多种方法详解
2020/09/17 NodeJs
JS效率个人经验谈(8-15更新),加入range技巧
2007/01/09 Javascript
js 学习笔记(三)
2009/12/29 Javascript
JavaScript去掉空格的方法集合
2010/12/28 Javascript
JavaScript高级程序设计 XML、Ajax 学习笔记
2011/09/10 Javascript
javascript实现限制上传文件大小
2015/02/06 Javascript
浅谈JavaScript的Polymer框架中的behaviors对象
2015/07/29 Javascript
jQuery语法小结(超实用)
2015/12/31 Javascript
jQuery实现将div中滚动条滚动到指定位置的方法
2016/08/10 Javascript
AngularJS入门教程之数据绑定原理详解
2016/11/02 Javascript
Javascript 两种刷新方法以及区别和适用范围
2017/01/17 Javascript
vue-resource 拦截器(interceptor)的使用详解
2017/07/04 Javascript
Textarea输入字数限制实例(兼容iOS&安卓)
2017/07/06 Javascript
微信小程序用户自定义模版用法实例分析
2017/11/28 Javascript
NodeJS http模块用法示例【创建web服务器/客户端】
2019/11/05 NodeJs
在vue中封装方法以及多处引用该方法详解
2020/08/14 Javascript
小程序实现左滑删除的效果的实例代码
2020/10/19 Javascript
[01:12:53]完美世界DOTA2联赛PWL S2 Forest vs SZ 第一场 11.25
2020/11/26 DOTA
python正常时间和unix时间戳相互转换的方法
2015/04/23 Python
python运行时间的几种方法
2016/06/17 Python
python搭建虚拟环境的步骤详解
2016/09/27 Python
Python SQLite3简介
2018/02/22 Python
使用python进行拆分大文件的方法
2018/12/10 Python
通俗易懂了解Python装饰器原理
2020/09/17 Python
Python定时任务框架APScheduler原理及常用代码
2020/10/05 Python
PyTorch 中的傅里叶卷积实现示例
2020/12/11 Python
金讯Java笔试题目
2013/06/18 面试题
高三自我鉴定
2013/10/23 职场文书
求职简历推荐信范文
2013/12/02 职场文书
材料员岗位职责
2014/03/13 职场文书
文秘应届生求职信
2014/07/05 职场文书
幼儿教师远程研修感悟
2015/11/18 职场文书