pyasyncore library

1.0.5 · active · verified Tue Apr 14

pyasyncore is a compatibility library that re-introduces the `asyncore` module, which was removed from the Python standard library in version 3.12. It allows existing codebases that rely on `asyncore` to continue functioning on Python 3.12 and later. The current version is 1.0.5, with releases typically tied to Python version compatibility or critical bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic `asyncore` echo server. It creates a server that listens on `127.0.0.1:8080` and echoes back any data received from connected clients. Run this script, then connect with `nc 127.0.0.1 8080` in another terminal to test. This example is identical to how `asyncore` would have been used in Python versions prior to 3.12.

import asyncore
import socket

class EchoHandler(asyncore.dispatcher_with_send):
    def handle_read(self):
        data = self.recv(8192)
        if data:
            self.send(data)

class EchoServer(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)
        print(f"Echo server listening on {host}:{port}")

    def handle_accept(self):
        pair = self.accept()
        if pair is not None:
            sock, addr = pair
            print(f"Incoming connection from {repr(addr)}")
            handler = EchoHandler(sock)

if __name__ == "__main__":
    # Note: asyncore is blocking. For a simple example, it runs forever.
    # In a real application, you might run it in a separate thread 
    # or integrate it with other event loops (though this defeats its purpose).
    try:
        server = EchoServer('127.0.0.1', 8080)
        asyncore.loop()
    except KeyboardInterrupt:
        print("\nServer stopped.")

view raw JSON →