By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,659 Members | 1,939 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,659 IT Pros & Developers. It's quick & easy.

Asyncore

P: n/a
Is there any tutorial and docs with samples how to use asyncore module?
Thanks
Lad

Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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(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)
--------

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
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.