What is .handle_read() in asyncore Python3?

Overview

The handle_read function of the asyncore.dispatcher class (or any class that inherits this class) is fired whenever the asynchronous loop detects that a read() call on the socket will succeed - meaning there is data to be read. handle_read is an overrideable method of the class asyncore.dispatcher in the asyncore library. The asyncore.dispatcher class is a wrapper class for a non-blocking socket object that makes the socket object more useful.

Example

The following code snippet creates HTTPClient using the asyncore library and demonstrates fetching data from a web server:

import asyncore
class 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('CHECKPOINT 1')
asyncore.loop()
print('CHECKPOINT 2')

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 which 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 in the output data from server (starting with b') is always printed after Checkpoint 1, which, ensures that even though an instance of HTTPClient exists with a binded 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 firing handle_write and handle_read methods.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved