Does "server" asyncore need to use asynchat??

Fredrik Lundh fredrik at pythonware.com
Sat May 12 10:47:01 EDT 2001


Ron Johnson wrote:
> All the examples that I've seen at www.nightmare.com and in the
> Medusa source code that use asyncore also use asynchat.
>
> Are there any examples of asyncore-without-asynchat?

here's one: a simple internet time protocol server:

# asyncore-example-2.py
# from the python standard library, o'reilly, may 2001

import asyncore
import socket, time

# reference time
TIME1970 = 2208988800L

class TimeChannel(asyncore.dispatcher):

    def handle_write(self):
        t = int(time.time()) + TIME1970
        t = chr(t>>24&255) + chr(t>>16&255) + chr(t>>8&255) + chr(t&255)
        self.send(t)
        self.close()

class TimeServer(asyncore.dispatcher):

    def __init__(self, port=37):
        self.port = port
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(("", port))
        self.listen(5)
        print "listening on port", self.port

    def handle_accept(self):
        channel, addr = self.accept()
        TimeChannel(channel)

server = TimeServer(8037)
asyncore.loop()

see the book (or the eff-bot guide to the same product) for
more examples.

Cheers /F





More information about the Python-list mailing list