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.