Question

is there a way to check connection is established in asyncore?

once asyncore.loop() is called, how can I disconnect the communication between server?

can i just simply call close()?

Was it helpful?

Solution

Once asyncore.loop() is called, the control is handed over to event loop that runs.

Any code after the asyncore.loop() will be called only after the event loop has been shut down.

Event loop will react to various events and call handlers. To shutdown the event loop, you must call to stop in one of the event handler where it makes sense.

For ex: Take a look at the following example.

Code from : 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 is called inside one of the event handler - handle_read. In this case after the data has been received from the server. it disconnects itself.

References:

OTHER TIPS

is there a way to check connection is established in asyncore?

Using with sockets, you can overload handle_connect() method of asyncore.dispatcher to run when socket is connected:

import asyncore

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

If you prefer polling, read the variable connected in your asyncore.dispatcher:

myclient = MyClientConnection()
isConnected = myClient.connected
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top