有没有办法检查在asyncore中是否建立了连接?
调用asyncore.loop()后,如何断开服务器之间的通信?
我能简单地调用close()吗?
发布于 2010-11-11 07:55:30
一旦调用了asyncore.loop(),控制权就会移交给运行的事件循环。
只有在关闭事件循环之后,才会调用asyncore.loop()之后的任何代码。
事件循环将对各种事件和调用处理程序做出反应。若要关闭事件循环,必须在其中一个有意义的事件处理程序中调用以停止。
对于ex:请看下面的示例。
代码来自: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。在这种情况下,在已经从服务器接收到数据之后。它会自动断开连接。
参考文献:
发布于 2012-11-30 16:44:40
有没有办法检查asyncore中是否建立了连接?
使用with sockets,您可以重载asyncore.dispatcher的handle_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.connectedhttps://stackoverflow.com/questions/4150227
复制相似问题