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的yield和generator
Mar 10 Python
Python正则表达式匹配中文用法示例
Jan 17 Python
运行django项目指定IP和端口的方法
May 14 Python
python 按不同维度求和,最值,均值的实例
Jun 28 Python
python绘制直线的方法
Jun 30 Python
如何使用Python标准库进行性能测试
Jun 25 Python
与Django结合利用模型对上传图片预测的实例详解
Aug 07 Python
python RC4加密操作示例【测试可用】
Sep 26 Python
python使用yield压平嵌套字典的超简单方法
Nov 02 Python
Django中ORM找出内容不为空的数据实例
May 20 Python
一文读懂Python 枚举
Aug 25 Python
【超详细】八大排序算法的各项比较以及各自特点
Mar 31 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
PhpMyAdmin中无法导入sql文件的解决办法
2010/01/08 PHP
关于PHP语言构造器介绍
2013/07/08 PHP
非常实用的PHP常用函数汇总
2014/12/17 PHP
php简单生成随机数的方法
2015/07/30 PHP
PHP抓取淘宝商品的用户晒单评论+图片+搜索商品列表实例
2016/04/14 PHP
PHP中常用的魔术方法
2017/04/28 PHP
PHP使用openssl扩展实现加解密方法示例
2020/02/20 PHP
完整显示当前日期和时间的JS代码
2007/09/17 Javascript
真正的JQuery.ajax传递中文参数的解决方法
2011/05/28 Javascript
IE关闭时判断及AJAX注销案例学习
2013/02/18 Javascript
JS冒泡事件的快速解决方法
2013/12/16 Javascript
jquery获取对象的方法足以应付常见的各种类型的对象
2014/05/14 Javascript
JS实现无限级网页折叠菜单(类似树形菜单)效果代码
2015/09/17 Javascript
浅谈Angular的$q, defer, promise
2016/12/20 Javascript
Bootstrap表单制作代码
2017/03/17 Javascript
javascript Canvas动态粒子连线
2020/01/01 Javascript
Python黑魔法Descriptor描述符的实例解析
2016/06/02 Python
Python基于回溯法子集树模板解决数字组合问题实例
2017/09/02 Python
Tensorflow实现AlexNet卷积神经网络及运算时间评测
2018/05/24 Python
对python中array.sum(axis=?)的用法介绍
2018/06/28 Python
pytz格式化北京时间多出6分钟问题的解决方法
2019/06/21 Python
pandas.read_csv参数详解(小结)
2019/06/21 Python
Python传递参数的多种方式(小结)
2019/09/18 Python
pytorch 利用lstm做mnist手写数字识别分类的实例
2020/01/10 Python
中国领先的专业演出票务网:永乐票务
2016/08/29 全球购物
英国豪华真皮和布艺沙发销售网站:Darlings of Chelsea
2018/01/05 全球购物
物理教师自荐信范文
2013/12/28 职场文书
冰淇淋开店创业计划书
2014/02/01 职场文书
优秀本科生求职推荐信
2014/02/24 职场文书
安全生产目标责任书
2014/04/14 职场文书
《二泉映月》教学反思
2014/04/15 职场文书
2014年端午节演讲稿范文
2014/05/23 职场文书
大学生党员批评与自我批评范文
2014/10/14 职场文书
撤诉书怎么写
2015/05/19 职场文书
七年级英语教学反思
2016/02/15 职场文书
开发微信小程序之WXSS样式教程
2022/04/18 HTML / CSS