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编程之多态用法实例详解
May 19 Python
Python定义一个跨越多行的字符串的多种方法小结
Jul 19 Python
啥是佩奇?使用Python自动绘画小猪佩奇的代码实例
Feb 20 Python
python爬虫爬取微博评论案例详解
Mar 27 Python
python的pytest框架之命令行参数详解(上)
Jun 27 Python
Flask之pipenv虚拟环境的实现
Nov 26 Python
pytorch dataloader 取batch_size时候出现bug的解决方式
Feb 20 Python
django中的数据库迁移的实现
Mar 16 Python
使用pyecharts1.7进行简单的可视化大全
May 17 Python
python 多进程和协程配合使用写入数据
Oct 30 Python
一文搞懂如何实现Go 超时控制
Mar 30 Python
关于Python使用turtle库画任意图的问题
Apr 01 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 If Else(elsefi) 语句
2013/04/07 PHP
浅谈PHP中的面向对象OOP中的魔术方法
2017/06/12 PHP
基于Laravel 5.2 regex验证的正确写法
2019/09/29 PHP
JavaScript 动态生成方法的例子
2009/07/22 Javascript
jQuery学习笔记之jQuery选择器的使用
2010/12/22 Javascript
js获取当前地址 JS获取当前URL的示例代码
2014/02/26 Javascript
SWFObject基本用法实例分析
2015/07/20 Javascript
jQuery实现带有洗牌效果的动画分页实例
2015/08/31 Javascript
跟我学习javascript的函数和函数表达式
2015/11/16 Javascript
JavaScript+Java实现HTML页面转为PDF文件保存的方法
2016/05/30 Javascript
基于JQuery及AJAX实现名人名言随机生成器
2017/02/10 Javascript
nodejs搭建本地http服务器教程
2017/03/13 NodeJs
详解webpack es6 to es5支持配置
2017/05/04 Javascript
基于jQuery实现的Ajax 验证用户名唯一性实例代码
2017/06/28 jQuery
Vue中的$set的使用实例代码
2018/10/08 Javascript
jquery的$().each和$.each的区别
2019/01/18 jQuery
详解Vue源码学习之双向绑定
2019/04/10 Javascript
webgl实现物体描边效果的方法介绍
2019/11/27 Javascript
JS如何定义用字符串拼接的变量
2020/07/11 Javascript
基于JQuery和DWR实现异步数据传递
2020/10/16 jQuery
Python 文件操作的详解及实例
2017/09/18 Python
win10下Python3.6安装、配置以及pip安装包教程
2017/10/01 Python
详解django中使用定时任务的方法
2018/09/27 Python
Python装饰器用法实例分析
2019/01/14 Python
Django 使用easy_thumbnails压缩上传的图片方法
2019/07/26 Python
Python + Requests + Unittest接口自动化测试实例分析
2019/12/12 Python
Python之字符串的遍历的4种方式
2020/12/08 Python
台湾最大银发乐活百货:乐龄网
2018/05/21 全球购物
英国最大的宠物商店:Pets at Home
2019/04/17 全球购物
环保公益策划方案
2014/08/15 职场文书
最美孝心少年事迹材料
2014/08/15 职场文书
刑事辩护授权委托书范本
2014/10/17 职场文书
2015年电教工作总结
2015/05/26 职场文书
告知书格式
2015/07/01 职场文书
Django显示可视化图表的实践
2021/05/10 Python
Django实现drf搜索过滤和排序过滤
2021/06/21 Python