From Second Life Wiki
< Eventlet
Revision as of 15:32, 24 August 2007 by Which Linden (Talk | contribs)

Jump to: navigation, search


These are short examples demonstrating the use of Eventlet. They are also included in the examples directory of the source.

echo server

This is a simple server that listens on port 6000 and simply echoes back every input line it receives. Connect to it with: telnet localhost 6000 Terminate your connection by quitting telnet (typically Ctrl-] and then 'quit')

from eventlet import api

def handle_socket(client):
    print "client connected"
    while True:
        # pass through every non-eof line
       x = client.readline()
       if not x: break
       print "echoed", x
   print "client disconnected"

# server socket listening on port 6000
server = api.tcp_listener(('', 6000))
while True:
   new_sock, address = server.accept()
   # handle every new connection with a new coroutine
   api.spawn(handle_socket, new_sock)


web crawler

This is a simple web "crawler" that fetches a bunch of urls using a coroutine pool. It fetches as many urls at time as coroutines in the pool.

urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",

import time
from eventlet import coros, httpc, util
# replace socket with a cooperative coroutine socket because httpc
# uses httplib, which uses socket.  Removing this serializes the http
# requests, because the standard socket is blocking.

def fetch(url):
    # we could do something interesting with the result, but this is
    # example code, so we'll just report that we did it
    print "%s fetching %s" % (time.asctime(), url)
    print "%s fetched %s" % (time.asctime(), url)

pool = coros.CoroutinePool(max_size=4)
waiters = []
for url in urls:
    waiters.append(pool.execute(fetch, url))

# wait for all the coroutines to come back before exiting the process
for waiter in waiters: