如何从处理程序中退出异步调度程序?

问题描述:

我在docs中找不到这个,但是我怎么打算在不使用信号的情况下跳出asyncore.loop()如何从处理程序中退出异步调度程序?

在查看源代码后,这很快就解决了。感谢直接链​​接到源代码的文档!

有一个ExitNow异常,您可以简单地从应用程序提出,退出循环。

使用文档中的EchoHandler示例,我已将其修改为在接收数据时立即退出。

class EchoHandler(asyncore.dispatcher_with_send): 

    def handle_read(self): 
     data = self.recv(8192) 
     if data: 
      raise asyncore.ExitNow('Server is quitting!') 

另外,请记住,您可以赶上ExitNow让你的应用程序不养,如果你在网络内部使用它。这是我的一些来源:

def run(config): 
    instance = LockServer(config) 
    try: 
     asyncore.loop() 
    except asyncore.ExitNow, e: 
     print e 

asyncore循环也退出时没有连接,所以你可以关闭连接。如果你有多个连接,那么你可以使用asyncore.close_all()。

另一种方法是使用asyncore.loop调用的count参数。然后,您可以将asyncore.loop换成其他逻辑:

while(i_should_continue()): 
    asyncore.loop(count=1) 

这不会立即停止打开的连接或过早超时。但这可能是一件好事?我在启动侦听服务器时使用了这个功能。

+1

死亡这可能是正确的解决方案,如果你想停止从“循环外”的循环。上面的其他解决方案是用于停止循环内的循环。 –

试试这个:

服务器

一类(扩展asyncore.dispatcher):

class Server(asyncore.dispatcher): 

    def __init__(self, port): 
     asyncore.dispatcher.__init__(self) 

     self.host = socket.gethostname() 
     self.port = port 

     self.create_socket(socket.AF_INET, socket.SOCK_STREAM) 
     self.set_reuse_addr() 
     self.bind((self.host, self.port)) 
     self.listen(5) 
     print "[Server] Listening on {h}:{p}".format(h=self.host, p=self.port) 

    def handle_accept(self): 
     pair = self.accept() 
     if pair is not None: 
      sock, addr = pair 
      print "[ServerSocket] We got a connection from {a}".format(a=addr) 
      SocketHandler(sock) 

另一类为谁去管理服务器的线程(继承Thread)...检查在run()方法,也就是我们称之为asyncore.loop():

class ServerThread(threading.Thread): 
    def __init__(self, port): 
     threading.Thread.__init__(self) 
     self.server = Server(port) 

    def run(self): 
     asyncore.loop() 

    def stop(self): 
     self.server.close() 
     self.join() 

现在启动服务器:

# This is the communication server, it is going to listen for incoming connections, it has its own thread: 
s = ServerThread(PORT) 
s.start()    # Here we start the thread for the server 
print "Server is ready..." 
print "Is ServerThread alive? {t}".format(t=str(s.is_alive())) 
raw_input("Press any key to stop de server now...") 
print "Trying to stop ServerThread..." 
s.stop() 
print "The server will die in 30 seconds..." 

你会注意到,服务器不会立即死去......但它优雅地