我搜索并认为twisted的dataReceived方法无法返回,所以有没有办法返回数据,这样我可以在需要数据时调用dataReceived,还是有其他技术可以在需要时在其他用户定义方法中获取数据? / p>
答案 0 :(得分:0)
希望我已正确理解你的问题。
这是从活动协议dataReceived方法中获取消息的一种方法的超简化版本。我在我们的一台服务器上运行它以确保它正常工作
此示例使用协议写入的队列,并从线程读取以传输数据。
在此示例中,showMessage函数自动打印收到的消息。 您可以执行其他操作,例如允许消息在队列中累积,并且命令可以批量从队列中检索它们。
请记住,生产系统必须在单个dataReceived消息中允许多个消息。在生产场景中,您还可以使用一些更适合线程的进程间通信方法。话虽如此,我认为deque是线程安全的,它似乎按照我展示的方式工作。 (有关PMOTW
出列的更多信息from __future__ import print_function
from collections import deque
import threading
import time
from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol
class MsgReceiver(Protocol):
def __init__(self, myQueue):
self.myQueue = myQueue
def connectionMade(self):
print("Connection made!")
def dataReceived(self, msg):
self.myQueue.append(msg)
class MsgReceiverFactory(Factory):
def __init__(self, myQueue):
self.myQueue = myQueue
def buildProtocol(self, addr):
return MsgReceiver(self.myQueue)
def showMessages(myQueue):
while True:
time.sleep(1)
try:
msg = myQueue.popleft()
print(msg)
except IndexError:
print("No messages in the queue")
myQueue = deque()
factory = MsgReceiverFactory(myQueue)
p = threading.Thread(target=showMessages, args=(myQueue,))
p.daemon = True
p.start()
reactor.listenTCP(42000, factory)
reactor.run()