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

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

# 定义了滑动窗口的大小
WINMAX = 2048
nownum = 1
getnum = 1
lastuid = 1
count = 2
class USSClientProtocol(ussp.USSClientQueueProtocol):
    """建立一个USS客户机的协议处理"""
    def connectionMade(self):
        """连接成功后开始发送报文"""
        # 先发一个connect报文进行握手
        message = usspmsg.USSPMessage()
        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.sendDataToQueue(message)
        ussp.USSClientQueueProtocol.connectionMade(self)

    def on_ussp_connect_resp(self, message):
        """服务器返回了connect的resp报文"""
        defer.succeed(self.testserver())

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

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

    def testserver(self):
        """向服务器发的测试报文"""
        global nownum
        global count

        while nownum < count:
            message = usspmsg.USSPMessage()
            message.setMsgName('mail_counter')
            message.body.setField('uid',str(nownum))
            if self.factory.sendQueue.full():
                self.call = reactor.callLater(0, self.testserver)
                return
            else:
                self.factory.sendQueue.put_nowait(message)
                nownum += 1

        self.disconnect()

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

class USSClientFactory(protocol.ClientFactory):
    protocol = USSClientProtocol

    def __init__(self):
        # 滑动窗口的大小
        self.WINMAX = WINMAX
        # 等待发送的报文队列
        self.sendQueue = Queue.Queue(self.WINMAX)
        # 已经发出的报文序列ID
        self.sendMsg = []
        # 使用的消息ID
        self.sequence = 1

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print "Connection lost"
        reactor.stop()
        pass

def main():
    f = USSClientFactory()
    global count
    count = 0xff
    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()
