Differences

This shows you the differences between two versions of the page.

random:flask_and_gevent_websocket_mashup [2013/12/19 03:16] (current)
grant created
Line 1: Line 1:
 +======Flask and Gevent Websocket Mashup======
 +
 +Simplest example of Flask and Gevent Websocket used together.
 +
 +<code python>
 +from flask import Flask
 +from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
 +
 +app = Flask(__name__)
 +
 +class echo(WebSocketApplication):
 +    def on_message(self, message):
 +        self.ws.send(message)
 +
 +@app.route('/')
 +def hello():
 +    return """<!DOCTYPE html>
 +<html>
 +  <head>
 +    <script>
 +    window.onload = function() {
 +      var ws = new WebSocket("ws://localhost:8080/echo");
 +  
 +      ws.onmessage = function(evt) {
 +        var data = evt.data;
 +        var el = document.getElementById('response');
 +        el.innerHTML += '<li>' + data + '</li>';
 +      };
 +
 +      var el = document.getElementById('message');
 +      el.onkeypress = function (evt) {
 +        if (evt.which == 13) {
 +           ws.send(el.value);
 +           el.value = '';
 +        }
 +      };
 +    };
 +    </script>
 +  </head>
 +  <body>
 +    <h1>Echo Example</h1>
 +    <p>Type a message and press enter.</p>
 +    <input id="message" type="text"></input>
 +    <ol id="response">
 +      <li>Responses show here.</li>
 +    </ol>
 +  </body>
 +</html>"""
 +
 +routes = {'/': app,
 +          '/echo': echo}
 +
 +server = WebSocketServer(('', 8080), Resource(routes), debug=True)
 +server.serve_forever()
 +</code>
random/flask_and_gevent_websocket_mashup.txt · Last modified: 2013/12/19 03:16 by grant