Тестирование витого приложения - Загрузить клиент - PullRequest
3 голосов
/ 31 октября 2009

Я написал сервер на основе Twisted, и я хотел бы также протестировать его с использованием Twisted.

Но я бы хотел написать нагрузочный тест, запускающий несколько запросов одновременно.

Но я считаю, что я не получил концепции Twisted, главным образом на стороне клиента, потому что я застрял с этой проблемой:

    from twisted.internet import reactor, protocol
from threading import Thread
from twisted.protocols.basic import LineReceiver

__author__="smota"
__date__ ="$30/10/2009 17:17:50$"

class SquitterClient(LineReceiver):

    def connectionMade(self):
        self.sendLine("message from " % threading.current_thread().name);
        pass

    def connectionLost(self, reason):
        print "connection lost"

    def sendMessage(self, msg):
        for m in [ "a", "b", "c", "d", "e"]:
            self.sendLine(msg % " - " % m);

class SquitterClientFactory(protocol.ClientFactory):
    protocol = SquitterClient

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

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

def createAndRun():
    f = SquitterClientFactory()
    reactor.connectTCP("localhost", 4010, f)
    reactor.run(installSignalHandlers=0)

# this connects the protocol to a server runing on port 8000
def main():
    for n in range(0,10):
        th=Thread(target=createAndRun)
        th.start()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()

socket_client.py: 35: Предупреждение об устаревании: Reactor уже Бег! Это поведение устарело начиная с витой 8.0
reactor.run (installSignalHandlers = 0)

Чего мне не хватает?

Как это проверить?

Спасибо,

Samuel

1 Ответ

9 голосов
/ 01 ноября 2009

Непосредственной причиной вашей ошибки является то, что вы пытаетесь вызвать run () на реакторе несколько раз. Вы должны когда-либо только вызывать run () один раз. Я думаю, что вы ожидаете иметь несколько реакторов, каждый в своем собственном потоке, но на самом деле у вас есть только один. Плохо то, что иметь несколько реакторов сложно или невозможно - хорошо, что это также не нужно. На самом деле вам даже не нужно несколько потоков. Вы можете объединить несколько клиентских подключений в одном реакторе почти так же легко, как вы можете прослушивать несколько подключений.

Изменение вашего примера кода, что-то вроде следующего должно работать. Основная идея заключается в том, что вам не нужно несколько реакторов для одновременной работы. В любом случае, единственное, что может быть совместимо с обычной реализацией Python - это ввод-вывод.

from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver

__author__="smota"
__date__ ="$30/10/2009 17:17:50$"

class SquitterClient(LineReceiver):
    def connectionMade(self):
        self.messageCount = 0
        # The factory provides a reference to itself, we'll use it to enumerate the clients
        self.factory.n += 1
        self.name = "Client %d" %self.factory.n

        # Send initial message, and more messages a bit later
        self.sendLine("Client %s starting!" % self.name);
        reactor.callLater(0.5, self.sendMessage, "Message %d" %self.messageCount)

    def connectionLost(self, reason):
        print "connection lost"

    def sendMessage(self, msg):
        for m in [ "a", "b", "c", "d", "e"]:
            self.sendLine("Copy %s of message %s from client %s!" % (m, msg, self.name))
        if self.factory.stop:
            self.sendLine("Client %s disconnecting!" % self.name)
            self.transport.loseConnection()
        else:
            self.messageCount += 1
            reactor.callLater(0.5, self.sendMessage, "Message %d" %self.messageCount)

class SquitterClientFactory(protocol.ClientFactory):
    protocol = SquitterClient

    def __init__(self):
        self.n = 0
        self.stop = False

    def stopTest():
        self.stop = True

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

    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"

# this connects the protocol to a server running on port 8000
def main():
    # Create 10 clients

    f = SquitterClientFactory()
    for i in range(10):
        reactor.connectTCP("localhost", 8000, f)

    # Schedule end of test in 10 seconds
    reactor.callLater(10, f.stopTest)

    # And let loose the dogs of war
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()
...