2014-11-01 63 views
4

我正在使用websockets来查看是否可以将轮询更新替换为项目。我正在使用Flask-Sockets,我想通过Flask视图发出更新。从视图中发出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(): 
    # here I want to emit a message like ws.send(message) 
    return 'Hello World!' 

我环顾四周,我没有发现类似的事情。这可能吗?

+0

曾经找到答案?我也在寻找这 – 2015-11-23 14:13:51

+0

可悲的是我没有。我决定使用Server Sent Events,因为websockets不是我所需要的。 – kechapito 2015-12-01 16:05:36

+0

我在这里得到了答案:):https://stackoverflow.com/a/47526225/111510 – tiktuk 2017-11-28 15:21:26

回答

1

这是非常非常简单的演示实施例

在下面的例子中,每2秒,服务器发送消息到与更新的计数客户端。 emit函数的第一个参数告诉客户端调用哪个函数。

app.py

from flask import Flask, render_template 
from flask_socketio import SocketIO, emit 


app = Flask(__name__) 
app.config['SECRET_KEY'] = 'secret!' 
socketio = SocketIO(app) 
thread = None 


def background_thread(): 
    count = 0 
    while True: 
     socketio.sleep(2) 
     count += 1 
     socketio.emit('my_response', 
         {'data': 'Message from server', 'count': count}, 
         namespace='/test') 


@app.route('/') 
def index(): 
    return render_template('index.html') 


@socketio.on('connect', namespace='/test') 
def test_connect(): 
    global thread 
    if thread is None: 
     thread = socketio.start_background_task(target=background_thread) 
    emit('my_response', {'data': 'Connected', 'count': 0}) 


if __name__ == '__main__': 
    socketio.run(app, debug=True, host='0.0.0.0', port=5050) 

在您的客户端,你将不得不使用this。在这个例子中,我包含了CDN。同样为了演示的目的,我使用了jquery。

模板/ index.html的

<!DOCTYPE HTML> 
<html> 
<head> 
    <title>Flask-SocketIO Test</title> 
    <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script> 
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script> 
    <script type="text/javascript" charset="utf-8"> 
     $(document).ready(function() { 
      namespace = '/test'; 
      var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace); 
      // This will be called by server. 
      // Anonymous function will be executed and span with id "view" will be updated 
      socket.on('my_response', function(msg) { 
       $('span#view').text(msg.count); 
      }); 
     }); 
    </script> 
</head> 
<body> 
    <h1>Flask-SocketIO Simple Example</h1> 
    <p>Counter at server: <span id="view"></span></p> 
</a> 
</body> 
</html> 

当你运行这个使用python app.py,并参观http://127.0.0.1:5050,那么你应该看到中的插座动作。

演示的工作版本,请here

相关问题