如何从处理程序退出asyncore调度程序?

gak*_*gak 6 python asyncore

我在文档中找不到这个,但是我怎么打算在asyncore.loop()不使用信号的情况下突破?

gak*_*gak 8

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

有一个ExitNow异常,您可以从应用程序中提取,退出循环.

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

class EchoHandler(asyncore.dispatcher_with_send):

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

此外,请记住,ExitNow如果您在内部使用它,您的应用程序不会引起注意.这是我的一些来源:

def run(config):
    instance = LockServer(config)
    try:
        asyncore.loop()
    except asyncore.ExitNow, e:
        print e
Run Code Online (Sandbox Code Playgroud)


小智 6

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


小智 5

试试这个:

服务器的一个类(扩展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)
Run Code Online (Sandbox Code Playgroud)

要管理服务器的线程的另一个类(扩展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()
Run Code Online (Sandbox Code Playgroud)

现在启动服务器:

# 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..."
Run Code Online (Sandbox Code Playgroud)

你会注意到服务器不会立即死亡......但它会优雅地消失