3 A first asyncio application

 

This chapter covers

  • Using sockets to transfer data over a network
  • Using telnet to communicate with a socket-based application
  • Using selectors to build a simple event loop for non-blocking sockets
  • Creating a non-blocking echo server that allows for multiple connections
  • Handling exceptions in tasks
  • Adding custom shutdown logic to an asyncio application

In chapters 1 and 2, we introduced coroutines, tasks, and the event loop. We also examined how to run long operations concurrently and explored some of asyncio’s APIs that facilitate this. Up to this point however, we’ve only simulated long operations with the sleep function.

Since we’d like to build more than just demo applications, we’ll use some real-world blocking operations to demonstrate how to create a server that can handle multiple users concurrently. We’ll do this with only one thread, leading to a more resource-efficient and simpler application than other solutions that would involve threads or multiple processes. We’ll take what we’ve learned about coroutines, tasks, and asyncio’s API methods to build a working command-line echo server application using sockets to demonstrate this. By the end of this chapter, you’ll be able to build socket-based network applications with asyncio that can handle multiple users simultaneously with one thread.

3.1 Working with blocking sockets

3.2 Connecting to a server with Telnet

3.2.1 Reading and writing data to and from a socket

3.2.2 Allowing multiple connections and the dangers of blocking

3.3 Working with non-blocking sockets

3.4 Using the selectors module to build a socket event loop

3.5 An echo server on the asyncio event loop

3.5.1 Event loop coroutines for sockets

3.5.2 Designing an asyncio echo server

3.5.3 Handling errors in tasks

3.6 Shutting down gracefully

3.6.1 Listening for signals

3.6.2 Waiting for pending tasks to finish

Summary