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_connectis called when a connection is successfully established.handle_exptis called when a connection fails.handle_acceptis called when a connection request is made to a listening socket. The callback should call theacceptmethod to get the client socket.handle_readis called when there is data waiting to be read from the socket. The callback should call therecvmethod to get the data.handle_writeis called when data can be written to the socket. Use thesendmethod to write data.handle_closeis 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 tosys.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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access