How do I get this websocket example to work with F

2019-03-18 18:43发布

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?

1条回答
做个烂人
2楼-- · 2019-03-18 19:16

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
查看更多
登录 后发表回答