在 Twisted 中有 1 天的经验,我尝试安排消息发送以回复 tcp 客户端:
import os, sys, time
from twisted.internet import protocol, reactor
self.scenario = [(1, "Message after 1 sec!"), (4, "This after 4 secs"), (2, "End final after 2 secs")]
for timeout, data in self.scenario:
reactor.callLater(timeout, self.sendata, data)
print "waited %d time, sent %s\n"%(timeout, data)
现在它发送消息,但我有两个问题:
1)“超时”是从“现在”开始的,我想在之前的每个任务完成后(发送之前的消息)进行计数
2)我不知道如何在发送所有消息后关闭连接。如果我放置self.transport.loseConnection()
after callLater
它会立即关闭连接。
在之前的尝试中我没有使用reactor.callLater
, 但只有self.transport.write()
and time.sleep(n)
in for
环形。在这种情况下,所有消息都在所有超时过去后一起发送......这不是我想要的。
目的是等待客户端连接,等待超时1并发送消息1,等待超时2并发送消息2,...等等。在最终消息之后 - 关闭连接。