我开始使用Twisted进行异步编程,我遇到了这个简单的问题,我不知道如何处理。快速分解问题如下:
我尝试在单独的线程中运行I / O代码,但我无法弄清楚如何使操作无阻塞。有没有人对我如何解决这个问题有任何建议?
感谢您的时间!
编辑1.这是服务器2正在执行的代码(具有发出请求的I / O循环的代码)
# Not including the Twisted code
addr = ("Server 1's IP", "Server 1's Port Number")
# Server class implements the functions to make calls and callbacks that act on responses from Server 1
chordServer = Server(2, "This server's IP", "This Server's port")
server = internet.UDPServer(8468, chordServer.protocol)
server.setServiceParent(application)
def controlLoop(q):
command = None
while 1:
command = input("Enter command: \n 1) join network \n 2) leave network \n 3) store key \n 4) fetch key\n 5) exit\n")
if command == 1:
print ">>> Executing Join Network Comand!"
q.put(command)
elif command == 2:
print ">>> Executing Leave Network Comand!"
q.put(command)
elif command == 3:
continue
elif command == 4:
continue
elif command == 5:
q.put(command)
#time.sleep(1)
def main():
cmd_queue = Queue.Queue()
dj = threading.Thread(target=controlLoop, args=(cmd_queue,))
dj.start()
while 1:
cmd = cmd_queue.get()
if cmd == 5:
break # Only after breaking does the callback associated with the calls below execute
elif cmd == 1:
chordServer.joinNetwork(addr) # Async call to Server 1
elif cmd == 2:
chordServer.leaveNetwork() # Another possible Async call to Server 1
task.deferLater(reactor, 5, main)
答案 0 :(得分:0)
我猜你对Twisted有误解。在Twisted中,reactor运行一个主命令循环来处理所有事件。你自己实现了两个永不终止的循环。这样反应器回路永远不会再次到达,扭曲也无法工作。您需要的是使用延迟对象和回调。但是我知道Twisted很复杂并且涉及很多与“普通”编程不同的思考方式,这使得这个主题太复杂而无法在这里处理它。也许你应该做手指tutoria。它一步一步地教你基本概念:http://twistedmatrix.com/documents/current/core/howto/tutorial/index.html