我已经这样编辑了:
我的 curl 命令是:
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:5000/telepath
我想在每个客户上显示这个发布的数据。我在文档上尽我所能,但这对我来说并不容易。
这是我的脚本:
from quart import Quart, render_template, websocket
from functools import partial, wraps
from quart import request, redirect, url_for, copy_current_websocket_context
import asyncio
app = Quart(__name__)
connected_websockets = set()
def collect_websocket(func):
@wraps(func)
async def wrapper(*args, **kwargs):
global connected_websockets
queue = asyncio.Queue()
connected_websockets.add(queue)
try:
return await func(queue, *args, **kwargs)
finally:
connected_websockets.remove(queue)
return wrapper
async def broadcast(message):
for queue in connected_websockets:
await queue.put(message)
@app.route('/')
async def index():
return await render_template('index.html')
@app.websocket('/ws')
@collect_websocket
async def ws(queue):
print("$ $ $",queue)
while True:
data = await websocket.receive()
print("\n {}".format(data))
await websocket.send(f"echo {data}")
@app.route('/telepath', methods=['POST'])
async def telepath():
global connected_websockets
data = await request.get_json()
for queue in connected_websockets:
await queue.put(data["key1"])
return "\n Request Processed.\n"
if __name__ == '__main__':
app.run(port=5000)
和模板:
<!doctype html>
<html>
<head>
<title>My TEST</title>
</head>
<body>
<input type="text" id="message">
<button>Send</button>
<ul></ul>
<script type="text/javascript">
var ws = new WebSocket('ws://' + document.domain + ':' + location.port + '/ws');
ws.onmessage = function (event) {
var messages_dom = document.getElementsByTagName('ul')[0];
var message_dom = document.createElement('li');
var content_dom = document.createTextNode('Received: ' + event.data);
message_dom.appendChild(content_dom);
messages_dom.appendChild(message_dom);
};
var button = document.getElementsByTagName('button')[0];
button.onclick = function() {
var content = document.getElementsByTagName('input')[0].value;
ws.send(content);
};
document.addEventListener('DOMContentLoaded', function() {
var es = new EventSource('/telepath');
es.onmessage = function (event) {
var messages_dom = document.getElementsByTagName('ul')[0];
var message_dom = document.createElement('li');
var content_dom = document.createTextNode('Received: ' + event.data);
message_dom.appendChild(content_dom);
messages_dom.appendChild(message_dom);
};
});
let socket = new WebSocket("ws://localhost:5000/ws");
socket.onmessage = function(event) {
alert(`Data received: ${event.data}`);
};
</script>
</body>
</html>
我的最终目标是身份验证,并确定谁可以从服务器接收私人消息。
无法在 mozilla 或 chrome 客户端上通过 curl 传输发布的数据。