File: server.py

package info (click to toggle)
python-aiohttp 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,288 kB
  • ctags: 4,380
  • sloc: python: 27,221; makefile: 236
file content (62 lines) | stat: -rw-r--r-- 1,510 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3

import asyncio
import logging

from aiohttp import web


@asyncio.coroutine
def wshandler(request):
    ws = web.WebSocketResponse(autoclose=False)
    ok, protocol = ws.can_start(request)
    if not ok:
        return web.HTTPBadRequest()

    yield from ws.prepare(request)

    while True:
        msg = yield from ws.receive()

        if msg.type == web.MsgType.text:
            ws.send_str(msg.data)
        elif msg.type == web.MsgType.binary:
            ws.send_bytes(msg.data)
        elif msg.type == web.MsgType.close:
            yield from ws.close()
            break
        else:
            break

    return ws


@asyncio.coroutine
def main(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', wshandler)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 9001)
    print("Server started at http://127.0.0.1:9001")
    return app, srv, handler


@asyncio.coroutine
def finish(app, srv, handler):
    srv.close()
    yield from handler.finish_connections()
    yield from srv.wait_closed()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)s %(message)s')

    loop = asyncio.get_event_loop()
    app, srv, handler = loop.run_until_complete(main(loop))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.run_until_complete(finish(app, srv, handler))