What is dispatcher_with_send() in asyncore?

Overview

Python’s asyncore module allows you to create a network of clients and servers that communicate asynchronously over sockets. This eliminates the need for threads and simplifies the implementation. The following code may be used to import the asyncore module into your program:

import asnycore

dispatcher_with_send() is a dispatcher() subclass of the asyncore module, which means that dispatcher_with_send() inherits all behaviors and attributes of the dispatcher() class. The only function dispatcher_with_send() adds onto dispatcher() is a buffered output for a simple client. dispatcher() is a wrapper around the low-level socket that offers methods for creating connections, writing to them, reading from them, and closing them. To use the asynchronous socket supplied by asyncore, we require dispatcher(). You can read more about the dispatcher() function in Python documentationhttps://docs.python.org/3/.

Example

The code below demonstrates how you can use the dispatcher_with_send() function:

import asyncore
class HandleConnections(asyncore.dispatcher_with_send):
def handle_read(self):
data = self.recv(8192)
if data:
print('Reply sent to client: ', data)
self.send(data)
class Server(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
def handle_accepted_conn(self, sock, address):
print(' Address of the client that has connected with server %s' % repr(address))
handler = HandleConnections(sock)
server = Server('localhost', 8080)
asyncore.loop()

Explanation

The code sets up a server that can accept connections from other clients. The server creates a socket using the create_socket() function inbuilt in the dispatcher() class. Then, it uses bind() function to bind to the port 8080. It also uses the listen() function to listen for connections and each connection becomes an object of type HandleConnection() class. The connections are handled by receiving data using the recv() function and sending back data on the channel using send(). The code above is not executable because it runs into an infinite loop while waiting for connections.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved