Mastering Concurrency in Python by Quan Nguyen

Mastering Concurrency in Python by Quan Nguyen

Author:Quan Nguyen
Language: eng
Format: mobi, pdf
Tags: COM051220 - COMPUTERS / Programming / Parallel, COM048000 - COMPUTERS / Systems Architecture / Distributed Systems and Computing, COM051280 - COMPUTERS / Programming Languages / Java
Publisher: Packt Publishing
Published: 2018-11-27T06:35:00+00:00


# Serve requests until Ctrl+C is pressed

print('Serving on {}'.format(server.sockets[0].getsockname()))

try:

loop.run_forever()

except KeyboardInterrupt:

pass

# Close the server

server.close()

loop.run_until_complete(server.wait_closed())

loop.close()

We are using the familiar asyncio.get_event_loop() function to create an event loop for our asynchronous program. Then, we create a server for our communication by having that event loop call the create_server() method; this method takes in a subclass from the asyncio.Protocol class, an address for our server (in this case, it is our local host: 127.0.0.1), and finally, a port for that address (typically, 8888).

Note that this method does not create the server itself; it only initiates the process of creating the server asynchronously, and returns a coroutine that will finish the process. For this reason, we need to store the returned coroutine from the method in a variable (coro, in our case) and have our event loop run that coroutine. After printing out a message using the sockets attribute of our server object, we will run the event loop forever, in order to keep the server running, except for the case of a KeyboardInterrupt exception being invoked.

Finally, at the end of our program, we will handle the house cleaning portion of the script, which is closing the server gracefully. This is typically done by having the server object call the close() method (to initiate the closing process of the server) and using the event loop to run the wait_closed() method on the server object, to make sure that the server is properly closed. Finally, we close the event loop.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.