ex****@hope.cz wrote:
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(asy ncore.dispatche r):
def __init__(self, ip, port):
self.ip= ip
self.port = port
self.count = 0
asyncore.dispat cher.__init__(s elf)
self.create_soc ket(socket.AF_I NET, socket.SOCK_STR EAM)
self.bind((ip, port))
self.listen(5)
def writable(self):
return 0
def handle_read(sel f):
pass
def readable(self):
return self.accepting
def handle_connect( self):
pass
def handle_accept(s elf):
try:
conn, addr = self.accept()
except socket.error: # rare Linux error
print "Socket error on server accept()"
return
except TypeError: # rare FreeBSD3 error
print "EWOULDBLOC K exception on server accept()"
return
self.count += 1
handler = http_handler(co nn, addr, self, self.count)
def decrement(self) :
self.count -= 1
class http_handler(as yncore.dispatch er):
def __init__(self, conn, addr, server, count):
asyncore.dispat cher.__init__(s elf, sock=conn)
self.addr = addr
self.buffer = ""
self.time = time.time()
self.count = count
self.server = server
def handle_read(sel f):
rq = self.recv(1024)
self.buffer = """HTTP/1.0 200 OK Canned Response Follows
Content-Type: text/html
<HTML>
<HEAD>
<TITLE>Respon se 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(se lf):
sent = self.send(self. buffer)
self.buffer = self.buffer[sent:]
if len(self.buffer ) == 0:
self.close()
self.server.dec rement()
server = http_server('', 8080)
asyncore.loop(t imeout=4.0)
--------
regards
Steve
--
Steve Holden
http://www.holdenweb.com/
Python Web Programming
http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119