What is .loop() in asyncore Python3?
Overview
The loop function is defined in the asyncore class. The asyncore.loop function starts the underlying channel services. These channel services can be instances of classes that inherit the asyncore.dispatcher class or asyncore.async_chat class.
Syntax
asyncore.loop([timeout[, use_poll[, map[, count]]]])
Parameters (optional)
timeoutis an integer value that specifies a timeout interval in seconds for the underlyingpollorselectfunction calls. The default value is30seconds.use_pollis a boolean value, which, ifTrue, prioritizes thepollfunction call over theselectfunction call. The default value isFalse.mapis a dictionary that contains the channels that are to be watched by theasyncore.loop. If this parameter is not specified, a global map is used, which contains all instances of classes that inheritasyncore.dispatcherclass orasyncore.async_chatclass.countis an integer value that instructs theasyncore.loopto terminate after a specified number of channels have been closed. The default value isNone, which results inasyncore.loopterminating only if all channels have been closed.
Note: The
asyncore.loopfunction has no return value.
Example
The following code snippet creates an instance of HTTPClient and calls the asyncore.loop function:
import asyncoreclass HTTPClient(asyncore.dispatcher):def __init__(self, host, path):asyncore.dispatcher.__init__(self)self.create_socket()self.connect( (host, 80) )self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %(path, host), 'ascii')def handle_close(self):self.close()def handle_read(self):print(self.recv(8192))def handle_write(self):sent = self.send(self.buffer)self.buffer = self.buffer[sent:]client = HTTPClient('www.google.com', '/')print('Asyncore Loop Started')asyncore.loop()print('Asyncore Loop Ended')
In the example above, the class HTTPClient is inherited from the asyncore.dispatcher class.
In the __init__ method, a socket is created and connected to port 80 of the given host. The self.buffer variable defines a GET query that can be sent to the host to fetch data from it.
The handle_read function is defined to print out any data read from the socket onto the standard output, whereas the handle_write function is defined to write to the socket whenever there is data in self.buffer.
The client instantiates an instance of HTTPClient with www.google.com as the host, and then asyncore.loop runs.
Notice that the output data from the server (starting with b') is enclosed between Aysncore Loop Started and Asyncore Loop Ended. This implies that even though an instance of HTTPClient exists with a bound socket object, the data flow does not begin unless the asyncore.loop function is called.
This is because the asyncore.loop function is responsible for initiating the underlying channels for HTTPClient, and thereafter for firing the handle_write and handle_read methods.
Free Resources