我正在尝试使用 Kenneth reitz's Flask-Sockets 库,用于编写一个简单的 websocket 接口(interface)/服务器。这是我目前所拥有的。
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)
我期望发生的是当我转到默认的 flask 页面时,在我的例子中是 http://localhost:5000
,我会看到一个带有文本 hello 的警告框john
,但是我收到了 Firefox 错误。错误是 Firefox 无法与位于 ws://localhost:5000/echo 的服务器建立连接
。如何通过向 Web 服务器发送消息然后回显回复来使 hello john
显示在警告框中?
最佳答案
使用 gevent-websocket(参见 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()
或者使用 gunicorn 运行服务器(参见 Flask-Sockets Deployment ):
gunicorn -k flask_sockets.worker module_name:app
关于javascript - 如何让这个 websocket 示例与 Flask 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19899578/