手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

应用Python快速实现系统原型

[日期:2012-05-04] 来源:Linux社区  作者:taozc [字体:大 中 小]

四、  代码摘要

1.导入库文件

  1. import asyncore   
  2. import socket  
  3. import sys  

2.主通讯服务类

    类初始化时,创建socket连接,绑定在指定的端口上,并且可以设置最大的并发连接数,此处默认为10,最多可以同时为10个客户端服务。

    当客户端呼叫过来后,触发handle_accept方法,这里输出客户端IP地址和端口信息,启动处理线程类SecondaryServerSocket。

    客户端断开连接时,触发handle_colse方法,此方法也调用asyncore.dispatcher类的close方法,做一些善后处理工作。

  1. class MainServerSocket(asyncore.dispatcher):  
  2.     def __init__(self, port):  
  3.         asyncore.dispatcher.__init__(self)  
  4.         self.create_socket(socket.AF_INET, socket.SOCK_STREAM)  
  5.         self.bind(('',port))  
  6.         #可以通过配置文件来设置最大连接数,目前是10个连接   
  7.         self.listen(10)      #最大可以同时为N个客户端服务   
  8.     def handle_accept(self):  
  9.         newSocket, address = self.accept( )  
  10.         print( "新的连接,来自{}".format(address) )  
  11.         SecondaryServerSocket(newSocket)  
  12.     def handle_close(self):  
  13.         asyncore.dispatcher.close(self)  
3.处理线程类

    此类继承自asyncore.dispatcher_with_send,当客户端发送交易报文过来时,触发handle_read方法。

    在handle_read方法中,根据具体的通讯协议,分析交易报文,然后针对不同的交易类型,分别进行处理。最后,处理好的交易报文,下发给对应的客户端。

  1. class SecondaryServerSocket(asyncore.dispatcher_with_send):  
  2.     def handle_read(self):  
  3.         receivedHead = self.recv(4)  
  4.         if receivedHead:  
  5.             if (len(receivedHead)==4) and (receivedHead.isdigit() ):  
  6.                 print( "报文头接收成功,报文长度:{}...".format(receivedHead) )  
  7.                 receivedData = self.recv(int(receivedHead))  
  8.                 print( "指定长度报文内容接收成功..." )  
  9.                 #----------------------   
  10.                 #0.特殊交易处理:服务器退出   
  11.                 #----------------------   
  12.                 if ( len(receivedData)==4 ) and ( receivedData.lower().endswith("exit") ) :  
  13.                     self.close()  
  14.                     print( "接收到退出命令,服务器退出!" )  
  15.                     try:  
  16.                         asyncore.close_all()  
  17.                         return  
  18.                     except:  
  19.                         sys.exit(0)  
  20.                         return  
  21.                 #----------------------   
  22.                 #...正常交易的处理   
  23.                 #----------------------   
  24.                 。。。  
  25.             else:  
  26.                 self.close()  
  27.                 print( "接收到非法报文头!" )  
  28.                 for x in range(len(receivedHead)):  
  29.                     print hex(ord(receivedHead[x])) , " ",  
  30.                 print()  
  31.         else:   
  32.                 self.close( )  
  33.                   
  34.     def handle_close(self):  
  35.         print( "断开连接,来自{}.".format( self.getpeername( ) ) )  

4.主程序入口

    程序从这里启动,首先打印程序帮助信息,然后在指定的侦听端口上,启动主通讯服务线程。

  1. if __name__ == "__main__" :  
  2.     print __doc__  
  3.     MainServerSocket(3555)  
  4.     print( "服务器开始侦听..." )  
  5.     asyncore.loop( )  

[参考资料]

1、《Python入门指南》Release2.5b2,作者:Guido van Rossum,2006.07.11,Python中国用户论坛集体翻译。
下载见 http://www.linuxidc.com/Linux/2012-05/59602.htm

2、《Python核心编程》第二版,作者:(美)丘恩(Chun,W.J.),翻译:宋吉广,2008.07,北京:人民邮电出版社。
下载见 http://www.linuxidc.com/Linux/2012-05/59603.htm

3、《深入Python :Dive Into Python中文版》5.4b,作者:MarkPilgrim, Python中国用户论坛集体翻译,Updated 审校 (5.4b):2007 年6 月—9 月
下载见 http://www.linuxidc.com/Linux/2012-05/59604.htm

linux
相关资讯       python 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款