简体   繁体   English

循环http客户端python,扭曲

[英]loop http client python , twisted

I have A simple Client which sends a request to server and receives a response : 我有一个简单的客户端,它向服务器发送请求并接收响应:

 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

here in main, i am trying to send the request to server by invoking cl() 5 times in a while loop . 在这里主要,我试图通过在while loop调用cl() 5次将请求发送到服务器。 but i am receiving some error, what i am assuming is that i have not stopped the client hence reactor is not starting, how do i solve this problem 但是我收到一些错误,我假设是我没有停止client因此反应堆无法启动,我该如何解决这个问题

Unfortunately, the Twisted reactor cannot be restarted . 不幸的是,扭曲反应堆无法重启 Once you have done reactor.stop() you cannot do reactor.start() again. 一旦完成了reactor.stop() ,就无法再次执行reactor.start()

Instead you need to do something like chaining the runs so that the callback for one run finishing will cause the next run to be started, or then schedule the runs with reactor.callLater() . 相反,您需要执行诸如链接运行之类的操作,以使一次运行完成的回调将导致开始下一次运行,或者然后使用reactor.callLater()安排运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM