Skip to content

Commit 078b6eb

Browse files
committed
Add example for aiohttp.web websocket
1 parent d95b7ae commit 078b6eb

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

aiohttp/websocket.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def parse_message(buf):
112112
elif payload:
113113
raise WebSocketError(
114114
'Invalid close frame: {} {} {!r}'.format(fin, opcode, payload))
115-
return Message(OPCODE_CLOSE, '', '')
115+
return Message(OPCODE_CLOSE, 0, '')
116116

117117
elif opcode == OPCODE_PING:
118118
return Message(OPCODE_PING, payload, '')

examples/web_ws.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

Comments
 (0)