四、 代码摘要
1.导入库文件
- import asyncore
- import socket
- import sys
2.主通讯服务类
类初始化时,创建socket连接,绑定在指定的端口上,并且可以设置最大的并发连接数,此处默认为10,最多可以同时为10个客户端服务。
当客户端呼叫过来后,触发handle_accept方法,这里输出客户端IP地址和端口信息,启动处理线程类SecondaryServerSocket。
客户端断开连接时,触发handle_colse方法,此方法也调用asyncore.dispatcher类的close方法,做一些善后处理工作。
- class MainServerSocket(asyncore.dispatcher):
- def __init__(self, port):
- asyncore.dispatcher.__init__(self)
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
- self.bind(('',port))
- #可以通过配置文件来设置最大连接数,目前是10个连接
- self.listen(10) #最大可以同时为N个客户端服务
- def handle_accept(self):
- newSocket, address = self.accept( )
- print( "新的连接,来自{}".format(address) )
- SecondaryServerSocket(newSocket)
- def handle_close(self):
- asyncore.dispatcher.close(self)
此类继承自asyncore.dispatcher_with_send,当客户端发送交易报文过来时,触发handle_read方法。
在handle_read方法中,根据具体的通讯协议,分析交易报文,然后针对不同的交易类型,分别进行处理。最后,处理好的交易报文,下发给对应的客户端。
- class SecondaryServerSocket(asyncore.dispatcher_with_send):
- def handle_read(self):
- receivedHead = self.recv(4)
- if receivedHead:
- if (len(receivedHead)==4) and (receivedHead.isdigit() ):
- print( "报文头接收成功,报文长度:{}...".format(receivedHead) )
- receivedData = self.recv(int(receivedHead))
- print( "指定长度报文内容接收成功..." )
- #----------------------
- #0.特殊交易处理:服务器退出
- #----------------------
- if ( len(receivedData)==4 ) and ( receivedData.lower().endswith("exit") ) :
- self.close()
- print( "接收到退出命令,服务器退出!" )
- try:
- asyncore.close_all()
- return
- except:
- sys.exit(0)
- return
- #----------------------
- #...正常交易的处理
- #----------------------
- 。。。
- else:
- self.close()
- print( "接收到非法报文头!" )
- for x in range(len(receivedHead)):
- print hex(ord(receivedHead[x])) , " ",
- print()
- else:
- self.close( )
- def handle_close(self):
- print( "断开连接,来自{}.".format( self.getpeername( ) ) )
4.主程序入口
程序从这里启动,首先打印程序帮助信息,然后在指定的侦听端口上,启动主通讯服务线程。
- if __name__ == "__main__" :
- print __doc__
- MainServerSocket(3555)
- print( "服务器开始侦听..." )
- 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
