Mercurial > cosocket
changeset 2:f6f9cc0385be
Clients can now be coroutines too.
author | Atul Varma <varmaa@toolness.com> |
---|---|
date | Fri, 17 Apr 2009 16:04:21 -0700 |
parents | f1159b9ec823 |
children | 9e819377ce9f |
files | taw.py |
diffstat | 1 files changed, 26 insertions(+), 6 deletions(-) [+] |
line wrap: on
line diff
--- a/taw.py Fri Apr 17 15:18:19 2009 -0700 +++ b/taw.py Fri Apr 17 16:04:21 2009 -0700 @@ -18,15 +18,17 @@ def handle_accept(self): conn, addr = self.accept() - AsyncChatCoroutineBridge(conn, addr, self.__coroutineFactory()) + coroutine = self.__coroutineFactory(addr) + AsyncChatCoroutineBridge(coroutine, conn) class AsyncChatCoroutineBridge(asynchat.async_chat): - def __init__(self, conn, addr, coroutine): + def __init__(self, coroutine, conn = None): asynchat.async_chat.__init__(self, conn) self.set_terminator(None) - self.__coroutine = coroutine(addr) + self.__coroutine = coroutine self.__data = [] - self.__process_next_instruction() + if conn: + self.__process_next_instruction() def __process_next_instruction(self, feedback = None): try: @@ -46,6 +48,9 @@ elif instruction['op'] == 'close': self.close() + def handle_connect(self): + self.__process_next_instruction() + def initiate_send(self): asynchat.async_chat.initiate_send(self) if ((not self.ac_out_buffer) and @@ -62,6 +67,12 @@ data = ''.join(self.__data) self.__process_next_instruction(data) +class ChattyCoroutineClient(AsyncChatCoroutineBridge): + def __init__(self, addr, coroutine): + AsyncChatCoroutineBridge.__init__(self, coroutine) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.connect(addr) + class ChattyCoroutine(object): def receive(self, terminator = None, length = None): return {'op': 'receive', @@ -72,7 +83,13 @@ return {'op': 'send', 'content': content} -class LameHttpCoroutine(ChattyCoroutine): +class LameHttpClientCoroutineFactory(ChattyCoroutine): + def __call__(self): + yield self.send('GET / HTTP/1.1\r\n\r\n') + response = yield self.receive(terminator = '\r\n\r\n') + print response + +class LameHttpServerCoroutineFactory(ChattyCoroutine): def __call__(self, addr): req = yield self.receive(terminator = '\r\n\r\n') msg = 'hello %s.' % addr[0] @@ -83,5 +100,8 @@ if __name__ == '__main__': server = ChattyCoroutineServer(('127.0.0.1', 8071), - LameHttpCoroutine) + LameHttpServerCoroutineFactory()) + client_factory = LameHttpClientCoroutineFactory() + client = ChattyCoroutineClient(('www.google.com', 80), + client_factory()) server.run()