我可以用python twisted';s数据接收方法
我搜索并认为twisted的dataReceived方法无法返回,那么是否有任何方法可以返回数据,以便在需要数据时调用dataReceived,或者是否有任何其他技术可以在需要时在其他用户定义方法中获取数据?希望我正确理解了您的问题 下面是从活动协议dataReceived方法中获取消息的一种方法的超简化版本。我已经在我们的一台服务器上运行了它,以确保它正常工作 本例使用协议写入的队列和线程读取的队列来传输数据 在本例中,showMessage函数自动打印收到的消息。 您可以执行其他操作,例如允许消息在队列中累积,并在命令发出时从队列中批量检索消息 请记住,生产系统必须允许在单个dataReceived消息中包含多条消息。在生产场景中,您还可以使用一些更适合线程的进程间通信方法。话虽如此,我认为deque是线程安全的,并且它似乎按照我所展示的方式工作。(有关退出队列的更多信息,请访问我可以用python twisted';s数据接收方法,python,return,chat,twisted,Python,Return,Chat,Twisted,我搜索并认为twisted的dataReceived方法无法返回,那么是否有任何方法可以返回数据,以便在需要数据时调用dataReceived,或者是否有任何其他技术可以在需要时在其他用户定义方法中获取数据?希望我正确理解了您的问题 下面是从活动协议dataReceived方法中获取消息的一种方法的超简化版本。我已经在我们的一台服务器上运行了它,以确保它正常工作 本例使用协议写入的队列和线程读取的队列来传输数据 在本例中,showMessage函数自动打印收到的消息。 您可以执行其他操作,例如允
如果您认为这是一个有用的解决方案,也许您可以接受以下答案:-)
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()