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?
Using gevent-websocket (See gevent-websocket usage):
Or run the server using gunicorn (See Flask-Sockets Deployment):