Python实现的简单文件传输服务器和客户端


Posted in Python onApril 08, 2015

还是那个题目(题目和流程见java版本),感觉光用java写一点新意也没有,恰巧刚学习了python,何不拿来一用,呵呵:
服务器端:

import SocketServer, time 
 
class MyServer(SocketServer.BaseRequestHandler):  
  userInfo = {  
    'yangsq'  : 'yangsq',  
    'hudeyong' : 'hudeyong',  
    'mudan'   : 'mudan' }  
 
  def handle(self):  
    print 'Connected from', self.client_address  
      
    while True:  
      receivedData = self.request.recv(8192)  
      if not receivedData:  
        continue 
        
      elif receivedData == 'Hi, server':  
        self.request.sendall('hi, client')  
          
      elif receivedData.startswith('name'):  
        self.clientName = receivedData.split(':')[-1]  
        if MyServer.userInfo.has_key(self.clientName):  
          self.request.sendall('valid')  
        else:  
          self.request.sendall('invalid')  
            
      elif receivedData.startswith('pwd'):  
        self.clientPwd = receivedData.split(':')[-1]  
        if self.clientPwd == MyServer.userInfo[self.clientName]:  
          self.request.sendall('valid')  
          time.sleep(5)  
 
          sfile = open('PyNet.pdf', 'rb')  
          while True:  
            data = sfile.read(1024)  
            if not data:  
              break 
            while len(data) > 0:  
              intSent = self.request.send(data)  
              data = data[intSent:]  
 
          time.sleep(3)  
          self.request.sendall('EOF')  
        else:  
          self.request.sendall('invalid')  
            
      elif receivedData == 'bye':  
        break 
 
    self.request.close()  
      
    print 'Disconnected from', self.client_address  
    print 
 
if __name__ == '__main__':  
  print 'Server is started\nwaiting for connection...\n'  
  srv = SocketServer.ThreadingTCPServer(('localhost', 50000), MyServer)  
  srv.serve_forever()

说明:
line-55到line-58的作用就相当于java中某个类里面的main函数,即一个类的入口。
python中SocketServer module里提供了好多实用的现成的类,BaseRequestHandler就是一个,它的作用是为每一个请求fork一个线程,只要继承它,就有这个能力了,哈哈,真是美事。
当然,我们继承了BaseRequestHandler,就是override它的handle方法,就像java中继承了Thread后要实现run方法一样。实际上这个handle方法的内容和我们的java版本的run函数实现的完全一样。
line-30到line-43就是处理文件下载的主要内容了。看着都挺眼熟的呵:)
这里在文件发送完后发了一个“EOF”,告诉client文件传完了。
客户端:

import socket, time 
 
class MyClient:  
 
  def __init__(self):  
    print 'Prepare for connecting...'  
 
  def connect(self):  
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
    sock.connect(('localhost', 50000))  
 
    sock.sendall('Hi, server')  
    self.response = sock.recv(8192)  
    print 'Server:', self.response  
 
    self.s = raw_input("Server: Do you want get the 'thinking in python' file?(y/n):")  
    if self.s == 'y':  
      while True:  
        self.name = raw_input('Server: input our name:')  
        sock.sendall('name:' + self.name.strip())  
        self.response = sock.recv(8192)  
        if self.response == 'valid':  
          break 
        else:  
          print 'Server: Invalid username'  
 
      while True:  
        self.pwd = raw_input('Server: input our password:')  
        sock.sendall('pwd:' + self.pwd.strip())  
        self.response = sock.recv(8192)  
        if self.response == 'valid':  
          print 'please wait...'  
 
          f = open('b.pdf', 'wb')  
          while True:  
            data = sock.recv(1024)  
            if data == 'EOF':  
              break 
            f.write(data)  
              
          f.flush()  
          f.close()  
 
          print 'download finished'  
          break 
        else:  
          print 'Server: Invalid password'  
          
 
    sock.sendall('bye')  
    sock.close()  
    print 'Disconnected'  
 
if __name__ == '__main__':  
  client = MyClient()  
  client.connect()

line-34到line-41处理文件下载,client收到server的“EOF”信号后,就知道文件传完了。
最后需要说明一下python的文件,由于是内置类型,所以不想java那样有那么多的reader,writer,input,ouput啊。python中,在打开或建立一个文件时,主要是通过模式(mode)来区别的。
python的网络编程确实简单,因为它提供了各种功能的已经写好的类,直接继承就Ok了。
python还在学习中,上面的例子跑通是没问题,但写得肯定不够好,还得学习啊

Python 相关文章推荐
Python使用htpasswd实现基本认证授权的例子
Jun 10 Python
利用Django框架中select_related和prefetch_related函数对数据库查询优化
Apr 01 Python
Python优先队列实现方法示例
Sep 21 Python
Python字典操作详细介绍及字典内建方法分享
Jan 04 Python
python列表生成式与列表生成器的使用
Feb 23 Python
matplotlib subplots 调整子图间矩的实例
May 25 Python
Python基于sklearn库的分类算法简单应用示例
Jul 09 Python
对pandas中iloc,loc取数据差别及按条件取值的方法详解
Nov 06 Python
基于YUV 数据格式详解及python实现方式
Dec 09 Python
pymysql 插入数据 转义处理方式
Mar 02 Python
Python如何用wx模块创建文本编辑器
Jun 07 Python
pytorch快速搭建神经网络_Sequential操作
Jun 17 Python
操作Windows注册表的简单的Python程序制作教程
Apr 07 #Python
编写简单的Python程序来判断文本的语种
Apr 07 #Python
Python实现在线程里运行scrapy的方法
Apr 07 #Python
Python实现从脚本里运行scrapy的方法
Apr 07 #Python
Python自定义scrapy中间模块避免重复采集的方法
Apr 07 #Python
Python中用memcached来减少数据库查询次数的教程
Apr 07 #Python
Python3中常用的处理时间和实现定时任务的方法的介绍
Apr 07 #Python
You might like
php插入排序法实现数组排序实例
2015/02/16 PHP
php定义一个参数带有默认值的函数实例分析
2015/03/16 PHP
PHP中Session和Cookie是如何操作的
2015/10/10 PHP
Javascript玩转继承(三)
2014/05/08 Javascript
JS动态添加Table的TR,TD实现方法
2015/01/28 Javascript
基于js实现投票的实例代码
2015/08/04 Javascript
JS实现点击上移下移LI行数据的方法
2015/08/05 Javascript
Backbone.js框架中简单的View视图编写学习笔记
2016/02/14 Javascript
基于jQuery实现仿微博发布框字数提示
2016/07/27 Javascript
使用nodejs中httpProxy代理时候出现404异常的解决方法
2016/08/15 NodeJs
微信小程序获取手机号授权用户登录功能
2017/11/09 Javascript
vue 刷新之后 嵌套路由不变 重新渲染页面的方法
2018/09/13 Javascript
angularJs复选框checkbox选中进行ng-show显示隐藏的方法
2018/10/08 Javascript
Vue解析带html标签的字符串为dom的实例
2019/11/13 Javascript
javascript局部自定义鼠标右键菜单
2020/12/08 Javascript
通过Python 获取Android设备信息的轻量级框架
2017/12/18 Python
python ftp 按目录结构上传下载的实现代码
2018/09/12 Python
详解将Django部署到Centos7全攻略
2018/09/26 Python
Python网页正文转换语音文件的操作方法
2018/12/09 Python
使用python实现抓取腾讯视频所有电影的爬虫
2019/04/15 Python
基于python的selenium两种文件上传操作实现详解
2019/09/19 Python
python 画图 图例自由定义方式
2020/04/17 Python
Python如何使用神经网络进行简单文本分类
2021/02/25 Python
Bobbi Brown芭比波朗美国官网:化妆师专业彩妆保养品品牌
2016/08/18 全球购物
英国旅行箱包和行李箱购物网站:Travel Luggage & Cabin Bags
2019/08/26 全球购物
澳大利亚厨房和家用电器购物网站:Bing Lee
2021/01/11 全球购物
PyQt 如何创建自定义QWidget
2021/03/24 Python
职业规划书如何设计?
2014/01/09 职场文书
优良学风班总结材料
2014/02/08 职场文书
食品安全承诺书
2014/05/22 职场文书
法院反腐倡廉心得体会
2014/09/09 职场文书
企业委托书范本
2014/09/13 职场文书
小学教师求职信范文
2015/03/20 职场文书
2016民族团结先进个人事迹材料
2016/02/26 职场文书
2016年优秀少先队辅导员事迹材料
2016/02/26 职场文书
JavaScript事件的委托(代理)的用法示例详解
2022/02/18 Javascript