Mercurial > cosocket
view example.py @ 14:545927beb490
Added an example MIME multipart/mixed response to the example server.
author | Atul Varma <varmaa@toolness.com> |
---|---|
date | Sun, 19 Apr 2009 13:24:23 -0700 |
parents | 65482f4e2555 |
children | 71e093cafa69 |
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': yield until_sent('HTTP/1.1 200 OK\r\n' + 'Content-Type: multipart/mixed; ' + 'boundary="chunk"\r\n\r\n') i = 0 while 1: i += 1 ip = yield channels.until_message_received('global') msg = 'Got message %d from %s.\r\n' % (i, ip) yield until_sent('--chunk\r\n' + 'Content-Length: %d\r\n' % len(msg) + 'Content-Type: text/plain\r\n\r\n' + msg) 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()