diff options
Diffstat (limited to 'examples/simple_tcp_server.py')
-rw-r--r-- | examples/simple_tcp_server.py | 36 |
1 files changed, 21 insertions, 15 deletions
diff --git a/examples/simple_tcp_server.py b/examples/simple_tcp_server.py index b796d9b..882938e 100644 --- a/examples/simple_tcp_server.py +++ b/examples/simple_tcp_server.py @@ -8,9 +8,11 @@ in the same process. It listens on port 1234 on 127.0.0.1, so it will fail if this port is currently in use. """ +from __future__ import print_function import sys -import asyncio +import trollius as asyncio import asyncio.streams +from trollius import From, Return class MyServer: @@ -58,28 +60,31 @@ class MyServer: out one or more lines back to the client with the result. """ while True: - data = (yield from client_reader.readline()).decode("utf-8") + data = (yield From(client_reader.readline())) + data = data.decode("utf-8") if not data: # an empty string means the client disconnected break - cmd, *args = data.rstrip().split(' ') + parts = data.rstrip().split(' ') + cmd = parts[0] + args = parts[1:] if cmd == 'add': arg1 = float(args[0]) arg2 = float(args[1]) retval = arg1 + arg2 - client_writer.write("{!r}\n".format(retval).encode("utf-8")) + client_writer.write("{0!r}\n".format(retval).encode("utf-8")) elif cmd == 'repeat': times = int(args[0]) msg = args[1] client_writer.write("begin\n".encode("utf-8")) for idx in range(times): - client_writer.write("{}. {}\n".format(idx+1, msg) + client_writer.write("{0}. {1}\n".format(idx+1, msg) .encode("utf-8")) client_writer.write("end\n".encode("utf-8")) else: - print("Bad command {!r}".format(data), file=sys.stderr) + print("Bad command {0!r}".format(data), file=sys.stderr) # This enables us to have flow control in our connection. - yield from client_writer.drain() + yield From(client_writer.drain()) def start(self, loop): """ @@ -115,32 +120,33 @@ def main(): @asyncio.coroutine def client(): - reader, writer = yield from asyncio.streams.open_connection( - '127.0.0.1', 12345, loop=loop) + reader, writer = yield From(asyncio.streams.open_connection( + '127.0.0.1', 12345, loop=loop)) def send(msg): print("> " + msg) writer.write((msg + '\n').encode("utf-8")) def recv(): - msgback = (yield from reader.readline()).decode("utf-8").rstrip() + msgback = (yield From(reader.readline())) + msgback = msgback.decode("utf-8").rstrip() print("< " + msgback) - return msgback + raise Return(msgback) # send a line send("add 1 2") - msg = yield from recv() + msg = yield From(recv()) send("repeat 5 hello") - msg = yield from recv() + msg = yield From(recv()) assert msg == 'begin' while True: - msg = yield from recv() + msg = yield From(recv()) if msg == 'end': break writer.close() - yield from asyncio.sleep(0.5) + yield From(asyncio.sleep(0.5)) # creates a client and connects to our server try: |