What is handle_write in asyncore Python3?

Overview

The handle_write function of the asyncore.dispatcher class (or any class that inherits this class) is fired whenever the asynchronous loop detects that a writable socket can be written. handle_write 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_write function is defined to send whatever is in self.buffer to the server and then shrink self.buffer with the sent amount. The data sent back from the server to our client is printed out on the screen due to the way handle_read function is defined. 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.

Copyright ©2024 Educative, Inc. All rights reserved