Skip to content

Instantly share code, notes, and snippets.

@mgdm
Created August 7, 2015 16:12
Show Gist options
  • Save mgdm/84a3c63ce9cd13666250 to your computer and use it in GitHub Desktop.
Save mgdm/84a3c63ce9cd13666250 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<body>
<script>
var socket = new WebSocket("ws://" + window.location.host + "/ws");
socket.onopen = function(event) {
socket.send("Hello there");
}
socket.onmessage = function(event) {
console.log(event);
console.log(event.data);
}
</script>
</body>
</html>
import asyncio
import aiohttp
from aiohttp import web
# Run with:
# gunicorn ws:app -w 2 -k aiohttp.worker.GunicornWebWorker -b 0.0.0.0:8085
@asyncio.coroutine
def handle_ws(request):
ws = web.WebSocketResponse()
ws.start(request)
try:
while True:
msg = yield from ws.receive()
ws.send_str(msg.data)
except Exception as e:
import traceback
traceback.print_exc()
return ws
@asyncio.coroutine
def index(request):
return aiohttp.web.HTTPFound('/index.html')
app = aiohttp.web.Application()
app.router.add_route('GET', '/ws', handle_ws)
app.router.add_route('GET', '/', index)
app.router.add_static('/', 'public')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment