#!/usr/bin/env python
# -*- coding: utf-8; test-case-name: compass.test.test_uss -*-
#
# $Id: ussd.py,v 1.5 2004/11/15 07:03:09 xyb Exp $
"""实现了USS的Daemon程序
"""

from uss.message import usspmsg
from uss.protocols import ussp
from twisted.internet import reactor, protocol
from time import clock

class USSServerProtocol(ussp.USSProtocol):
    """建立一个USS服务器的协议处理"""
    def connectionMade(self):
        """建立连接了，先什么都不做"""
        pass

    def on_ussp_connect(self, message):
        """处理客户机connect报文"""
        smessage = usspmsg.USSPMessage()
        smessage.head.sequence = message.head.sequence
        smessage.setMsgName('connect_resp')
        smessage.body.setField('status',1)
        smessage.body.setField('version',1)
        self.sendData(smessage.packed())

    def on_ussp_mail_counter(self, message):
        """处理客户机发来的mail_counter报文"""
        smessage = usspmsg.USSPMessage()
        smessage.head.sequence = message.head.sequence
        smessage.setMsgName('mail_counter_resp')
        smessage.body.setField('uid',message.body.fields['uid'])
        smessage.body.setField('number',2028)
        self.sendData(smessage.packed())

    def on_ussp_terminate(self, message):
        """处理客户机terminate报文"""
        smessage = usspmsg.USSPMessage()
        smessage.head.sequence = message.head.sequence
        smessage.setMsgName('terminate_resp')
        self.sendData(smessage.packed())
        # 完事了！！！断开丫的连接
        self.transport.loseConnection()

class USSServerFactory(protocol.ServerFactory):
    """USS服务器工厂"""
    protocol = USSServerProtocol

def main():
    f = USSServerFactory()
    reactor.listenTCP(7890, f)
    reactor.run()

if __name__ == "__main__":
    main()
