我试图使用
Kenneth reitz’s 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无法建立到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()
或使用爆米花运行服务器(请参阅Flask-Sockets Deployment):
gunicorn -k flask_sockets.worker module_name:app