| 1 |
import asyncio |
| 2 |
import aiorpcx |
| 3 |
|
| 4 |
|
| 5 |
# Handlers are declared as normal python functions. aiorpcx automatically checks RPC |
| 6 |
# arguments, including named arguments, and returns errors as appropriate |
| 7 |
async def handle_echo(message): |
| 8 |
return message |
| 9 |
|
| 10 |
|
| 11 |
async def handle_sum(*values): |
| 12 |
return sum(values, 0) |
| 13 |
|
| 14 |
|
| 15 |
handlers = { |
| 16 |
'echo': handle_echo, |
| 17 |
'sum': handle_sum, |
| 18 |
} |
| 19 |
|
| 20 |
|
| 21 |
class ServerSession(aiorpcx.RPCSession): |
| 22 |
|
| 23 |
def __init__(self, *args, **kwargs): |
| 24 |
super().__init__(*args, **kwargs) |
| 25 |
print(f'connection from {self.remote_address()}') |
| 26 |
|
| 27 |
async def connection_lost(self): |
| 28 |
await super().connection_lost() |
| 29 |
print(f'{self.remote_address()} disconnected') |
| 30 |
|
| 31 |
async def handle_request(self, request): |
| 32 |
handler = handlers.get(request.method) |
| 33 |
coro = aiorpcx.handler_invocation(handler, request)() |
| 34 |
return await coro |
| 35 |
|
| 36 |
|
| 37 |
loop = asyncio.get_event_loop() |
| 38 |
loop.run_until_complete(aiorpcx.serve_ws(ServerSession, 'localhost', 8889)) |
| 39 |
loop.run_forever() |