我正在尝试使用肯尼思·雷茨的 http://kennethreitz.org/introducing-flask-sockets/Flask-Sockets 库用于编写简单的 websocket 接口/服务器。这是我到目前为止所拥有的。
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)
我期望发生的是当我进入默认烧瓶页面时,http://localhost:5000
就我而言,我会看到一个带有文本的警告框hello john
,但是我收到了 Firefox 错误。错误是Firefox can't establish a connection to the server at ws://localhost:5000/echo
。我该如何制作hello john
通过向 Web 服务器发送消息然后回显回复来显示在警报框中?
使用 gevent-websocket(参见gevent-websocket 使用 http://www.gelens.org/code/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 部署 https://github.com/kennethreitz/flask-sockets#deployment):
gunicorn -k flask_sockets.worker module_name:app
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)