我有一个简单的客户端,它向服务器发送请求并收到响应:
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
这里在main中,我试图通过在cl()
中调用while loop
5次来将请求发送到服务器。但我收到一些错误,我假设是我没有停止client
因此反应堆没有启动,我该如何解决这个问题
答案 0 :(得分:1)
不幸的是,扭曲的反应堆cannot be restarted。完成reactor.stop()
后,您无法再次reactor.start()
。
相反,您需要执行诸如链接运行之类的操作,以便一次运行完成的回调将导致下一次运行开始,或者使用reactor.callLater()
计划运行。