diff options
author | 2018-02-13 10:45:57 +0000 | |
---|---|---|
committer | 2018-02-13 10:45:57 +0000 | |
commit | cf999735856504fee0bfe74d9b66e764b71ae746 (patch) | |
tree | dd08cb6cc372b750732099e42e7f9b9b557d2b28 | |
parent | fix typo (diff) |
Websocket echo test
-rw-r--r-- | pysite/views/main/ws_test.py | 15 | ||||
-rw-r--r-- | requirements.txt | 2 | ||||
-rw-r--r-- | templates/ws_test.html | 24 | ||||
-rw-r--r-- | ws_app.py | 27 |
4 files changed, 68 insertions, 0 deletions
diff --git a/pysite/views/main/ws_test.py b/pysite/views/main/ws_test.py new file mode 100644 index 00000000..c28269a8 --- /dev/null +++ b/pysite/views/main/ws_test.py @@ -0,0 +1,15 @@ +# coding=utf-8 +import os + +from pysite.base_route import RouteView + + +class WSTest(RouteView): + path = "/ws_test" + name = "ws_test" + + def get(self): + return self.render( + "ws_test.html", + server_name=os.environ.get("SERVER_NAME", "localhost") + ) diff --git a/requirements.txt b/requirements.txt index ccf9ac97..4ae185cd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,5 @@ rethinkdb requests gevent gevent-websocket +wsaccel +ujson diff --git a/templates/ws_test.html b/templates/ws_test.html new file mode 100644 index 00000000..fd8dd3a3 --- /dev/null +++ b/templates/ws_test.html @@ -0,0 +1,24 @@ +{% extends "base.html" %} +{% block title %}WS Test{% endblock %} +{% block content %} + <div class="uk-container uk-section"> + <h1>Open your JS console to test</h1> + + <script type="application/javascript"> + let ws = new WebSocket("ws://api.{{ server_name }}/ws/echo"); + + ws.onopen = function(event) { + console.log("WS opened! Use send() to send a message."); + }; + + ws.onmessage = function (event) { + console.log("<- " + event.data); + }; + + function send(text) { + console.log("-> " + text); + ws.send(text); + } + </script> + </div> +{% endblock %}
\ No newline at end of file diff --git a/ws_app.py b/ws_app.py new file mode 100644 index 00000000..a9f60175 --- /dev/null +++ b/ws_app.py @@ -0,0 +1,27 @@ +# coding=utf-8 + +from collections import OrderedDict + +from geventwebsocket import Resource, WebSocketApplication, WebSocketServer + + +class EchoApplication(WebSocketApplication): + def on_open(self): + print("Connection opened") + + def on_message(self, message, **kwargs): + print(f"<- {message}") + self.ws.send(message) + print(f"-> {message}") + + def on_close(self, reason): + print(reason) + + +if __name__ == "__main__": + app = WebSocketServer( + ('', 8000), + Resource(OrderedDict([('/ws/echo', EchoApplication)])) + ) + + app.serve_forever() |