What is ExitNow() in asyncore?

Overview

The asyncore module in Python allows you to build a network of clients and servers that communicate asynchronously over sockets. This eliminates the need for threads and simplifies the implementation. Include the following code in your program to import the asyncore module:

import asnycore

ExitNow() is a class of the asyncore module that exits the asyncore.loop(). The asnycore loop is what enables all the channels to communicate through an asynchronous socket. ExitNow() is defined as the following in the asyncore module:

class ExitNow(Exception):
    pass

Example

Below is an example of how you can use the ExitNow() 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)
raise asyncore.ExitNow('Shutting down server')
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

In the code above, while a server is listening for connections and handling every separate connection in the HandleConnections class, the ExitNow() exception is raised the first time the server receives and sends data back to a client.

Copyright ©2024 Educative, Inc. All rights reserved