Below is a simple Websockets Echo Server using Flask and gevent 🙂
Installation
requirements.txt – easily build all depencies
1 2 3 4 5 6 7 8 |
cat > requirements.txt <<"_EOF_" flask greenlet gevent gevent-websocket _EOF_ sudo pip install -U -r requirements.txt |
websocket_echo_test.py – main server file
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 |
cat > websocket_echo_test.py <<"_EOF_" # coding: utf-8 import os import json from gevent.pywsgi import WSGIServer from geventwebsocket.handler import WebSocketHandler import flask app = flask.Flask(__name__, template_folder='./') app.secret_key = os.urandom(24) app.debug = True host,port='localhost',8000 @app.route('/') def index(): return flask.render_template('index.html', port=port) def wsgi_app(environ, start_response): path = environ["PATH_INFO"] if path == "/": return app(environ, start_response) elif path == "/websocket": handle_websocket(environ["wsgi.websocket"]) else: return app(environ, start_response) def handle_websocket(ws): while True: message = ws.receive() if message is None: break message = json.loads(message) ws.send(json.dumps({'output': message['output']})) if __name__ == '__main__': http_server = WSGIServer((host,port), wsgi_app, handler_class=WebSocketHandler) print('Server started at %s:%s'%(host,port)) http_server.serve_forever() _EOF_ |
index.html – HTML template
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 |
cat > index.html <<"_EOF_" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script> $(function() { if ("WebSocket" in window) { ws = new WebSocket("ws://" + document.domain + ":{{port}}/websocket"); ws.onmessage = function (msg) { var message = JSON.parse(msg.data); $("p#log").html(message.output ); }; }; $('input[name=text]').on('keyup', function(e){ e.preventDefault(); var message = $(this).val(); ws.send(JSON.stringify({'output': message})); }); $('input[name=text]').focus(); window.onbeforeunload = function() { ws.onclose = function () {}; ws.close() }; }); </script> <style> input { font-size: 48px; width: 600px; border-style: none; background-color: transparent; border-style: solid; border-width: 0px 0px 1px 0px; } textarea:focus, input:focus{ outline: 0; } </style> </head> <body> <input type="text" name="text" /> <p id="log"></p> <p>--<br/>Websockets Echo Server using Gevent-websocket & Flask</p> </body> </html> _EOF_ |
Start Server
1 |
python websocket_echo_test.py |
Browser URL
1 |
http://localhost:8000 |
References
1. Flask
2. Gevent
3. Websockets