有没有办法检查连接在异步中?

一旦调用了asyncore.loop(),我如何才能断开服务器之间的通信?

我可以简单地调用Close()吗?

有帮助吗?

解决方案

一旦调用了asyncore.loop(),将控件移交给运行的事件循环。

仅在关闭事件循环后,ASYNCORE.LOOP()之后的任何代码才会被调用。

事件循环将对各种事件做出反应并致电处理程序。 要关闭事件循环,您必须打电话在事件处理程序之一中停止,那里有意义。

例如:请查看以下示例。

代码来自: http://www.mechanicalcat.net/richard/log/python/a_simple_asyncore_echo_server__example

import asyncore, socket

class Client(asyncore.dispatcher_with_send):
    def __init__(self, host, port, message):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))
        self.out_buffer = message

    def handle_close(self):
        self.close()

    def handle_read(self):
        print 'Received', self.recv(1024)
        self.close()

c = Client('', 5007, 'Hello, world')
asyncore.loop()

self.close被称为事件处理程序之一 - handle_read。在这种情况下,在从服务器收到数据之后。它断开了自己的连接。

参考:

其他提示

有没有办法检查连接在异步中?

使用插座,您可以超载 hander_connect() 的方法 asyncore.dispatcher 连接插座时运行:

import asyncore

class MyClientConnection(asyncore.dispatcher):
    def handle_connect(self):
        '''Socket is connected'''
        print "Connection is established"

如果您喜欢投票,请阅读变量 连接的 在您的Asyncore.dispatcher中:

myclient = MyClientConnection()
isConnected = myClient.connected
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top