The asyncore Module

The asyncore module provides a reactive socket implementation. Instead of creating socket objects and calling methods on them to do things, this module allows you to write code that is called when something can be done. To implement an asynchronous socket handler, subclass the dispatcher class, and override one or more of the following methods:

  • handle_connect is called when a connection is successfully established.

  • handle_expt is called when a connection fails.

  • handle_accept is called when a connection request is made to a listening socket. The callback should call the accept method to get the client socket.

  • handle_read is called when there is data waiting to be read from the socket. The callback should call the recv method to get the data.

  • handle_write is called when data can be written to the socket. Use the send method to write data.

  • handle_close is called when the socket is closed or reset.

  • handle_error(type, value, traceback) is called if a Python error occurs in any of the other callbacks. The default implementation prints an abbreviated traceback to sys.stdout.

Example 7-7 shows a time client, similar to the one for the socket module.

Example 7-7. Using the asyncore Module to Get the Time from a Time Server

File: asyncore-example-1.py import asyncore import socket, time # reference time (in seconds since 1900-01-01 00:00:00) TIME1970 = 2208988800L # 1970-01-01 00:00:00 class TimeRequest(asyncore.dispatcher): # time requestor (as defined in RFC 868) ...

Get Python Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.