Is there any tutorial and docs with samples how to use asyncore module?
Thanks
Lad
Well, here's a very simple web server from Chapter 7 of "Python Web
Programming" which might help get you started.
You can see a few more examples if you download the code from the book,
which you can do at
http://pydish.holdenweb.com/pwp/download.htm
--------
import socket
import asyncore
import time
class http_server(asyncore.dispatcher):
def __init__(self, ip, port):
self.ip= ip
self.port = port
self.count = 0
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind((ip, port))
self.listen(5)
def writable(self):
return 0
def handle_read(self):
pass
def readable(self):
return self.accepting
def handle_connect(self):
pass
def handle_accept(self):
try:
conn, addr = self.accept()
except socket.error: # rare Linux error
print "Socket error on server accept()"
return
except TypeError: # rare FreeBSD3 error
print "EWOULDBLOCK exception on server accept()"
return
self.count += 1
handler = http_handler(conn, addr, self, self.count)
def decrement(self):
self.count -= 1
class http_handler(asyncore.dispatcher):
def __init__(self, conn, addr, server, count):
asyncore.dispatcher.__init__(self, sock=conn)
self.addr = addr
self.buffer = ""
self.time = time.time()
self.count = count
self.server = server
def handle_read(self):
rq = self.recv(1024)
self.buffer = """HTTP/1.0 200 OK Canned Response Follows
Content-Type: text/html
<HTML>
<HEAD>
<TITLE>Response from server</TITLE>
</HEAD>
<BODY>
<P>This is socket number %d
</BODY>
""" % self.count
def writable(self):
if time.time()-self.time > 10:
return len(self.buffer) > 0
else:
return 0
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
if len(self.buffer) == 0:
self.close()
self.server.decrement()
server = http_server('', 8080)
asyncore.loop(timeout=4.0)