我试图让一些代码工作,但似乎无法正确处理,目的是所有客户端都可以在按下按钮时看到。
目前,我可以让按下按钮的客户看到消息,但没有其他消息。
派:
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}));
});
});
欣赏新鲜的观点。