Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is ExitNow() in asyncore?

Samia Ishaque

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python

CONTRIBUTOR

Samia Ishaque
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring