1

我有一个简单的客户端,它向服务器发送请求并接收响应:

 from StringIO import StringIO

 from twisted.internet import reactor
 from twisted.internet.protocol import Protocol
 from twisted.web.client import Agent
 from twisted.web.http_headers import Headers
 from twisted.internet.defer import Deferred
 from twisted.web.client import FileBodyProducer

 import log , time

class server_response(Protocol):
     def __init__(self, finished):
         self.finished = finished
         self.remaining = 1024 * 10

     def dataReceived(self, bytes):
         if self.remaining:
            reply = bytes[:self.remaining]
            print "reply from server:" , reply
            log.info(reply)

     def connectionLost(self, reason):
          #print 'Finished receiving body:', reason.getErrorMessage()
          self.finished.callback(None)

def capture_response(response): 

    finished = Deferred()
    response.deliverBody(server_response(finished))
    return finished

def cl():

    xml_str = "<xml>"
    agent = Agent(reactor)
    body = FileBodyProducer(StringIO(xml_str))
    d = agent.request(
        'PUT',
        'http://localhost:8080/',
        Headers({'User-Agent': ['Replication'],
                'Content-Type': ['text/x-greeting']}),
        body)

    d.addCallback(capture_response)

    def cbShutdown(ignored):
        reactor.stop()

   d.addBoth(cbShutdown)
       reactor.run()

if __name__ == '__main__':

     count = 1
     while (count < 5) :
     print count
     cl()
     time.sleep(2)
     count = count + 1

这里主要是,我试图通过cl()在 a 中调用 5 次来将请求发送到服务器while loop。但我收到一些错误,我假设我没有停止client因此反应堆没有启动,我该如何解决这个问题

4

1 回答 1

1

不幸的是,Twisted reactor无法重新启动。一旦你做了reactor.stop()你就不能再做reactor.start()

相反,您需要执行链接运行之类的操作,以便一次运行完成的回调将导致下一次运行开始,或者然后使用reactor.callLater().

于 2014-09-11T08:10:09.107 回答