0

我试图让一些代码工作,但似乎无法正确处理,目的是所有客户端都可以在按下按钮时看到。

目前,我可以让按下按钮的客户看到消息,但没有其他消息。

派:

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}));
    });


});

欣赏新鲜的观点。

4

1 回答 1

0

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

于 2013-12-26T21:22:05.007 回答