Sling Academy
Home/Python/Python: How to create your own asyncio TCP server (and test it using cURL)

Python: How to create your own asyncio TCP server (and test it using cURL)

Last updated: February 11, 2024

Python offers several optimizations and improvements, especially in the realm of asynchronous programming. In this tutorial, we’ll dive into creating an asyncio TCP server in modern Python, demonstrating the power and simplicity asyncio offers for handling networking tasks. We’ll also explore how to test our server using cURL, a versatile command-line tool for transferring data with URLs.

Understanding asyncio

Before we begin, it’s crucial to understand what asyncio is and why it’s beneficial for network programming. Asyncio is a Python library that provides a framework for writing single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources. It allows for efficient handling of large numbers of connections, making it perfect for creating servers.

Setting Up Your Environment

Start by ensuring you have Python 3.11 or newer installed on your machine. You can check this by running:

python --version

If you don’t have it, download and install it from the official Python website. This tutorial assumes basic familiarity with Python syntax and the command line.

Creating the Echo Server

We’ll start by creating a simple echo server that listens on a specific port and echoes back whatever data is sent to it. This example is perfect for understanding the basics of an asyncio TCP server. Here’s a basic server setup:

import asyncio

async def handle_client(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')
    print(f"Received {message} from {addr}")

    writer.write(data)
    await writer.drain()
    writer.close()

async def main():
    server = await asyncio.start_server(
        handle_client, '127.0.0.1', 8888)
    addr = server.sockets[0].getsockname()
    print(f'Serving on {addr}')

    async with server:
        await server.serve_forever()

asyncio.run(main())

This code snippet defines an echo server with asyncio. The handle_client coroutine reads data from the client, prints it, then sends the same data back. The server listens on localhost port 8888.

Testing with cURL

Once our server is running, we can test it using cURL. cURL is typically used for HTTP requests, but it also supports sending raw data to a TCP server, which is perfect for our test. Here’s how you can do it:

curl -v telnet://localhost:8888

Following this command, you can type your message and press Enter. The server will echo back your input. Note that you might need to press Enter twice because of how TCP is framed.

Expanding The Server

Building on the echo server, you can create more sophisticated asynchronous TCP servers handling complex logic. For instance, you could modify handle_client to parse incoming messages as commands and interact with databases or other network services asynchronously.

Error Handling

It’s essential to handle potential errors in network programming. You can add exception handling in handle_client like so:

async def handle_client(reader, writer):
    try:
        data = await reader.read(100)
        # ... handle data
    except Exception as e:
        print(f'An error occurred: {e}')
    finally:
        writer.close()

This addition helps ensure that the writer is closed properly even if an error occurs, preventing resource leaks.

Conclusion

This tutorial covered creating a simple asyncio TCP server in Python and testing it with cURL. Asynchronous programming can significantly enhance the performance and scalability of network applications, and asyncio with Python makes it more accessible and powerful than ever. Experiment with the provided examples, and consider how you can apply asyncio’s capabilities to your projects.

Next Article: Python: How to type hint asynchronous functions

Previous Article: Python asyncio: How to download a large file and show progress (percentage)

Series: Python Asynchronous Programming Tutorials

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types