使用Flask在客户端之间传递变量

时间:2013-10-23 04:34:19

标签: python flask

我正在尝试使用一些代码,但似乎无法正确使用,目的是所有客户端都可以看到按下按钮的时间。

目前,我可以让按下按钮的客户端看到消息而不是其他消息。

PY:

pushedDict = {}    

@app.route('/buttons/')
def index():
    return flask.render_template('index.html', port=port)

def wsgi_app(environ, start_response):  
    path = environ["PATH_INFO"]  
    if path == "/buttons/":  
        return app(environ, start_response)
    elif path == "/websocket/":  
        handle_websocket(environ["wsgi.websocket"])
    else:  
        return app(environ, start_response)  


def handle_websocket(ws):
    while True:
        pushRecieve = ws.receive()    # Receive pushed Buttons 
        gap = "Button"    # Placeholder for later
        pushedDict.update({gap:pushRecieve})    # Add to Dictionary
        pushSend = json.loads(pushedDict[gap])    # Get from Dictionary
        ws.send(json.dumps({'output': pushSend['output']}))    # Send 
        pushedDict.update({gap:""})    # Clear Dictionary

JS收到:

$(document).ready(function(){                                            

    $(function() {
        if ("WebSocket" in window) {
            ws = new WebSocket("ws://" + document.domain + ":{{port}}/websocket/");
            ws.onmessage = function (msg) {
                var getButtons = JSON.parse(msg.data);
                $("p#log").html(getButtons.output );
            };
        };
    });

JS发送:

    var buttonQueue = [];

    $("a.button1").mousedown(function(e){
        e.preventDefault();
        buttonQueue.push("button1")
        ws.send(JSON.stringify({'output': buttonQueue}));
    });
    $("a.button1").mouseup(function(e){
        e.preventDefault();
        remove(buttonQueue, "button1");
        ws.send(JSON.stringify({'output': buttonQueue}));
    });
    $("a.button2").mousedown(function(e){
        e.preventDefault();
        buttonQueue.push("button2")
        ws.send(JSON.stringify({'output': buttonQueue}));
    });
    $("a.button2").mouseup(function(e){
        e.preventDefault();
        remove(buttonQueue, "button2");
        ws.send(JSON.stringify({'output': buttonQueue}));
    });


});

欣赏新的观点。

1 个答案:

答案 0 :(得分:0)

我不是WebSockets的专家,但我的印象是ws协议只建立客户端和服务器之间的持续连接,允许从服务器发送数据而无需客户端的持续请求。您的Flask应用程序不知道任何其他连接的客户端;它一次只使用handle_websocket(ws)与一个客户端通信。 你必须告诉你的Flask应用程序当前连接了哪些客户端,然后ws.send()按钮按下更新所有这些。我对此没有任何经验,但它看起来像跟踪ws连接客户端并发送更新的最常用方法是redis。我还找到了一个可以根据您的需求调整的示例chat application。希望这有帮助!