diff --git a/examples/ws.html b/examples/ws.html
new file mode 100644
index 00000000..c57ca6d0
--- /dev/null
+++ b/examples/ws.html
@@ -0,0 +1,20 @@
+
+
+
+ WebSocket demo
+
+
+
+
+
diff --git a/examples/ws.py b/examples/ws.py
new file mode 100644
index 00000000..20772ca0
--- /dev/null
+++ b/examples/ws.py
@@ -0,0 +1,21 @@
+import asyncio
+import sanic
+from sanic.response import html
+import datetime
+import random
+
+app = sanic.Sanic()
+
+async def time(websocket, path):
+ while True:
+ now = datetime.datetime.utcnow().isoformat() + 'Z'
+ await websocket.send(now)
+ await asyncio.sleep(random.random() * 3)
+
+app.websocket(time, 'localhost', 3000)
+
+@app.route('/')
+def hello(request):
+ return html(open('ws.html').read())
+
+app.run(port=8000)
diff --git a/requirements.txt b/requirements.txt
index 724a5835..e370b52f 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -2,3 +2,4 @@ aiofiles
httptools
ujson
uvloop
+websockets
diff --git a/sanic/sanic.py b/sanic/sanic.py
index 951632be..4d629e02 100644
--- a/sanic/sanic.py
+++ b/sanic/sanic.py
@@ -17,6 +17,7 @@ from .response import HTTPResponse
from .router import Router
from .server import serve, serve_multiple, HttpProtocol
from .static import register as static_register
+import websockets
class Sanic:
@@ -44,7 +45,7 @@ class Sanic:
self._blueprint_order = []
self.debug = None
self.sock = None
- self.processes = None
+ self.before_start = None
# Register alternative method names
self.go_fast = self.run
@@ -53,6 +54,14 @@ class Sanic:
# Registration
# -------------------------------------------------------------------- #
+ # Register a websocket server
+ def websocket(self, handler, host='0.0.0.0', port=3000):
+ server = websockets.serve(handler, host, port)
+
+ def before_start(app, loop):
+ get_event_loop().run_until_complete(server)
+ self.before_start = before_start
+
# Decorator
def route(self, uri, methods=frozenset({'GET'}), host=None):
"""
@@ -397,6 +406,14 @@ class Sanic:
:param protocol: Subclass of asyncio protocol class
:return: Nothing
"""
+ if self.before_start is not None:
+ _before_start = before_start
+
+ def _before(app, loop):
+ if _before_start is not None:
+ _before_start(app, loop)
+ self.before_start(app, loop)
+ before_start = _before
server_settings = self._helper(
host=host, port=port, debug=debug, before_start=before_start,
after_start=after_start, before_stop=before_stop,
diff --git a/tox.ini b/tox.ini
index 4155e909..62fc531a 100644
--- a/tox.ini
+++ b/tox.ini
@@ -14,6 +14,7 @@ deps =
aiohttp
pytest
beautifulsoup4
+ websockets
commands =
pytest tests {posargs}