【问题标题】:python asyncore connectivitypython异步连接
【发布时间】:2010-11-10 23:51:53
【问题描述】:

有没有办法检查异步中是否建立了连接?

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

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

【问题讨论】:

    标签: python asyncore


    【解决方案1】:

    一旦 asyncore.loop() 被调用,控制权就会移交给运行的事件循环。

    asyncore.loop() 之后的任何代码只有在事件循环关闭后才会被调用。

    事件循环将对各种事件和调用处理程序做出反应。 要关闭事件循环,您必须在有意义的事件处理程序之一中调用 stop。

    例如:看看下面的例子。

    代码来自: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 中被调用。在这种情况下,在从服务器接收到数据之后。它会自行断开连接。

    参考资料:

    【讨论】:

    • 如何设置异步循环在互联网死后重新连接并重新出现?就好像在失去连接后没有收到新数据一样,它仍然处于开启状态。
    【解决方案2】:

    有没有办法检查异步中是否建立了连接?

    使用sockets,你可以重载asyncore.dispatcherhandle_connect()方法在socket连接时运行:

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

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

    myclient = MyClientConnection()
    isConnected = myClient.connected
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 2021-12-17
      • 2023-04-08
      • 2010-09-07
      • 2020-11-26
      • 2015-01-15
      • 1970-01-01
      相关资源
      最近更新 更多