Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get this websocket example to work with Flask?

I'm trying to use Kenneth reitz's Flask-Sockets library to write a simple websocket interface/server. Here is what I have so far.

from flask import Flask
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)

@sockets.route('/echo')
def echo_socket(ws):

    while True:
        message = ws.receive()
        ws.send(message)


@app.route('/')
def hello():
    return \
'''
<html>

    <head>
        <title>Admin</title>

        <script type="text/javascript">
            var ws = new WebSocket("ws://" + location.host + "/echo");
            ws.onmessage = function(evt){ 
                    var received_msg = evt.data;
                    alert(received_msg);
            };

            ws.onopen = function(){
                ws.send("hello john");
            };
        </script>

    </head>

    <body>
        <p>hello world</p>
    </body>

</html>
'''

if __name__ == "__main__":

    app.run(debug=True)

What I am expecting to happen is when I go to the default flask page, http://localhost:5000 in my case, I will see an alert box with the text hello john, however instead I get a Firefox error. The error is Firefox can't establish a connection to the server at ws://localhost:5000/echo. How do I make hello john show up in the alert box by sending a message to the web server then echoing the reply?

like image 789
John Avatar asked Nov 11 '13 05:11

John


People also ask

Can flask handle WebSockets?

Flask, being a minimalist web framework, does not have WebSocket support built-in. The old Flask-Sockets extension, which has not been maintained in the last few years, provided support for this protocol.

How do I activate WebSockets?

- In Control Panel, click Programs and Features, and then click Turn Windows features on or off. Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then select WebSocket Protocol. Click OK. Click Close.

How do I connect to WebSocket connection?

In order to communicate using the WebSocket protocol, you need to create a WebSocket object; this will automatically attempt to open the connection to the server. The URL to which to connect; this should be the URL to which the WebSocket server will respond.


1 Answers

Using gevent-websocket (See gevent-websocket usage):

if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()

Or run the server using gunicorn (See Flask-Sockets Deployment):

gunicorn -k flask_sockets.worker module_name:app
like image 151
falsetru Avatar answered Sep 28 '22 03:09

falsetru