|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Example for aiohttp.web websocket server |
| 3 | +""" |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import os |
| 7 | +from aiohttp.web import (Application, Response, |
| 8 | + WebSocketResponse, WebSocketDisconnectedError) |
| 9 | + |
| 10 | +WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html') |
| 11 | + |
| 12 | + |
| 13 | +@asyncio.coroutine |
| 14 | +def handler(request): |
| 15 | + resp = WebSocketResponse() |
| 16 | + ok, protocol = resp.can_start(request) |
| 17 | + if not ok: |
| 18 | + with open(WS_FILE, 'rb') as fp: |
| 19 | + return Response(body=fp.read(), content_type='text/html') |
| 20 | + |
| 21 | + resp.start(request) |
| 22 | + print('{}: Someone joined.'.format(os.getpid())) |
| 23 | + for ws in request.app['sockets']: |
| 24 | + ws.send_str('Someone joined') |
| 25 | + request.app['sockets'].append(resp) |
| 26 | + |
| 27 | + try: |
| 28 | + while True: |
| 29 | + msg = yield from resp.receive_str() |
| 30 | + print(msg) |
| 31 | + for ws in request.app['sockets']: |
| 32 | + if ws is not resp: |
| 33 | + ws.send_str(msg) |
| 34 | + except WebSocketDisconnectedError: |
| 35 | + request.app['sockets'].remove(resp) |
| 36 | + print('Someone disconnected.') |
| 37 | + for ws in request.app['sockets']: |
| 38 | + ws.send_str('Someone disconnected.') |
| 39 | + raise |
| 40 | + |
| 41 | + |
| 42 | +@asyncio.coroutine |
| 43 | +def init(loop): |
| 44 | + app = Application(loop=loop) |
| 45 | + app['sockets'] = [] |
| 46 | + app.router.add_route('GET', '/', handler) |
| 47 | + |
| 48 | + srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 8080) |
| 49 | + print("Server started at http://127.0.0.1:8080") |
| 50 | + return srv |
| 51 | + |
| 52 | +loop = asyncio.get_event_loop() |
| 53 | +loop.run_until_complete(init(loop)) |
| 54 | +loop.run_forever() |
0 commit comments