简体   繁体   English

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

[英]Passing variables between clients with Flask

I'm trying to get some code to work but can't seem to get it right, The intention is that all the clients can see when a button is pushed. 我正在尝试使一些代码正常工作,但似乎无法正确处理,其目的是当按下按钮时所有客户端都可以看到。

At the moment I can get the client that presses the button to see the message but no other. 目前,我可以让客户按下按钮来查看消息,但没有其他消息。

Py: 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 Receive: 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 Send: 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}));
    });


});

Appreciate a fresh point of view. 欣赏新鲜的观点。

I'm no expert on WebSockets, but my impression is that the ws protocol only establishes an ongoing connection between client and server, allowing data to be sent from the server without constant requests from the client. 我不是WebSockets方面的专家,但是我的印象是ws协议仅在客户端和服务器之间建立了持续的连接,从而允许从服务器发送数据而无需客户端不断发出请求。 Your Flask app doesn't know about any other clients connected; 您的Flask应用程序不知道有任何其他客户端连接; it only uses handle_websocket(ws) to talk to one client at a time. 它只使用handle_websocket(ws)一次与一个客户端通信。 You have to tell your Flask app which clients are currently connected, then ws.send() the button press updates to all of them. 您必须告诉Flask应用程序当前连接了哪些客户端,然后通过ws.send()按钮更新所有客户端。 I don't have any experience with this, but it looks like the most popular way to track ws-connected clients and send them updates is redis . 我对此没有任何经验,但是看起来跟踪WS连接的客户端并向其发送更新的最流行的方法是redis I also found an example chat application that you could adapt for your needs. 我还找到了一个示例聊天应用程序 ,可以满足您的需求。 Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM