#!/usr/bin/env python
# -*- coding: utf-8; test-case-name: compass.test.test_gns -*-
#
# $Id: gnsc.py,v 1.6 2004/11/15 07:03:09 xyb Exp $
"""实现了Global Name Service的Client程序
"""
from compass.uss.message import gnspmsg
from compass.uss.protocols import gnsp
from twisted.internet import reactor, protocol, defer
from time import clock

nownum = 1
getnum = 1
lastuid = 1
class GNSClientProtocol(gnsp.GNSProtocol):
    """建立一个USS客户机的协议处理"""
    def connectionMade(self):
        """连接成功后开始发送报文"""
        # 先发一个connect报文进行握手
        message = gnspmsg.GNSPMessage()
        message.setMsgName('connect')
        message.body.setField('system_id','123456')
        message.body.setField('auth_source','1234567890123456')
        message.body.setField('version',0x0100)
        message.body.setField('time_stamp','12345678')
        self.sendData(message.packed())

    def on_gnsp_connect_resp(self, message):
        """服务器返回了connect的resp报文"""
        # print "Connect successfully"
        defer.succeed(self.testserver())

    def on_gnsp_terminate_resp(self, message):
        # 完事了！！！断开丫的连接
        self.transport.loseConnection()

    def on_gnsp_mail_counter_resp(self, message):
        """服务器返回了mail_counter的resp报文"""
        global getnum
        global lastuid
        lastuid = message.body.fields['uid']
        getnum += 1
        self.disconnect()

    def testserver(self):
        """向服务器发的测试报文"""
        global nownum
        message = gnspmsg.GNSPMessage()
        message.setMsgName('mail_counter')
        message.body.setField('uid',str(nownum))
        self.sendData(message.packed())
        nownum += 1

    def disconnect(self):
        """发完测试报文后发送terminate报文让服务器断开连接"""
        message = gnspmsg.GNSPMessage()
        message.setMsgName('terminate')
        self.sendData(message.packed())

class GNSClientFactory(protocol.ClientFactory):
    protocol = GNSClientProtocol

    def clientConnectionFailed(self, connector, reason):
        global nownum
        global count
        if nownum < count:
            connector.connect()
        else:
            print "Connection failed - goodbye!"
            reactor.stop()


    def clientConnectionLost(self, connector, reason):
        global nownum
        global count
        if nownum < count:
            connector.connect()
        else:
            print "Connection lost"
            reactor.stop()

def main():
    f = GNSClientFactory()
    global count
    count = 0xf
    global nownum
    nownum = 0
    global lastuid
    lastuid = ''
    global getnum
    getnum = 0
    reactor.connectTCP("127.0.0.1", 7890, f)
    start = clock()
    reactor.run()
    print "测试数据：%10d 条" %nownum
    print "收到 %d 条" %getnum
    print "最后收到uid为：%s" %lastuid
    print "用时：%.2f 秒" %(clock()-start)
    print "每秒：%f条" %(nownum / (clock()-start))

if __name__ == "__main__":
    main()
