view example.py @ 13:65482f4e2555

Added a really simple channel communication system, somewhat similar to that of Stackless.
author Atul Varma <varmaa@toolness.com>
date Sun, 19 Apr 2009 12:55:38 -0700
parents 1ffa6554ff3a
children 545927beb490
line wrap: on
line source

from cosocket import *
import channels

def _make_http_response(msg):
    return ('HTTP/1.1 200 OK\r\n' +
            'Content-Length: %d\r\n' % len(msg) +
            'Content-Type: text/plain\r\n\r\n' +
            msg)

def example_http_server_coroutine(addr):
    request_line = yield until_received(terminator = '\r\n')
    request_headers = yield until_received(terminator = '\r\n\r\n')
    req_parts = request_line.split()
    if req_parts[1] == '/listen':
        ip = yield channels.until_message_received('global')
        yield until_sent(_make_http_response('send from %s.' % ip))
    elif req_parts[1] == '/send':
        yield channels.until_message_sent('global', addr[0])
        yield until_sent(_make_http_response('sent.'))
    else:
        yield until_sent(_make_http_response('hello %s.' % addr[0]))

def _example_nested_coroutine():
    chunk = yield until_received(bytes = 20)
    print 'first chunk : %s' % repr(chunk)
    chunk = yield until_received(bytes = 20)
    print 'second chunk: %s' % repr(chunk)

def example_http_client_coroutine(addr):
    yield until_sent('GET / HTTP/1.1\r\n\r\n')
    response_headers = yield until_received(terminator = '\r\n\r\n')
    yield _example_nested_coroutine()
    chunk = yield until_received(bytes = 20)
    print 'third chunk : %s' % repr(chunk)

if __name__ == '__main__':
    server = CoroutineSocketServer(('127.0.0.1', 8071),
                                   example_http_server_coroutine)
    client = CoroutineSocketClient(('www.google.com', 80),
                                   example_http_client_coroutine)
    server.run()