python asyncore连接

时间:2010-11-10 23:51:53

标签: python asyncore

有没有办法检查连接是否在asyncore中建立?

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

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

2 个答案:

答案 0 :(得分:2)

调用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()

在一个事件处理程序 - handle_read中调用self.close。在这种情况下,从服务器收到数据后。它断开了自己。

参考文献:

答案 1 :(得分:0)

  

有没有办法检查连接是否在asyncore中建立?

使用套接字,您可以重载asyncore.dispatcher handle_connect()方法,以便在连接套接字时运行:

import asyncore

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

如果您更喜欢轮询,请阅读asyncore.dispatcher中的变量已连接

myclient = MyClientConnection()
isConnected = myClient.connected