add demo script using websockets and asyncio

This commit is contained in:
arne 2023-01-29 13:16:41 +01:00
parent 3ec9856ff8
commit d5f0b09fba
4 changed files with 51 additions and 5 deletions

5
app.py Normal file → Executable file
View File

@ -1,3 +1,4 @@
#!/usr/bin/env python3
from flask import Flask, render_template, url_for, request, redirect, Response, abort, session
from flask_sock import Sock
from flask_sqlalchemy import SQLAlchemy
@ -28,8 +29,8 @@ def get_date():
date = datetime.now()
return { "now": date.strftime("%Y-%m-%d") }
@sock.route('/<namespace>')
def echo(sock,namespace):
@sock.route('/')
def echo(sock):
while True:
data = json.loads(sock.receive())
sock.send(json.dumps({"method":"set","name":"test","value":"abcd"}))

View File

@ -3,13 +3,14 @@
<div id="data"></div>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
let socket = new WebSocket("ws://localhost:5000/testProject");
let socket = new WebSocket("ws://localhost:5000");
let projectID = "1234"; // hier project ID eintragen
function setVariable(name, value) {
console.log(`Setting variable: ${name} = ${value}`);
socket.send(JSON.stringify({
method: "set",
project_id: projectID,
name,
value
}));
@ -21,8 +22,10 @@
socket.send(JSON.stringify({
method: "handshake",
project_id: projectID,
user: "testClientHtml"
user: "testClient"+Math.random()
}));
setInterval(function() { setVariable('test',Math.random()) }, Math.random(3)*1000);
};
socket.onmessage = function(event) {

View File

@ -3,7 +3,7 @@
<div id="data"></div>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
let socket = new WebSocket("ws://localhost:5000/echo");
let socket = new WebSocket("ws://localhost:5000/");
socket.onopen = function(e) {
console.log("connection established");
socket.send("Hello World");

42
test.py Normal file
View File

@ -0,0 +1,42 @@
import asyncio
import websockets
import json
clients = {}
async def handshake(ws,j):
if not clients.get(j.get('project_id')):
clients[j.get('project_id')] = {}
clients[j.get('project_id')][j.get('user')] = ws
print(f"{j.get('user')} connected from {ws.host}:{ws.port}")
return(j.get('project_id'),j.get('user'))
async def set_variable(j):
for name,ws in clients.get(j.get('project_id'),{}).items():
print(f"> {name} - {json.dumps(j)}")
ws.send(json.dumps(j))
async def disconnect(project_id,user):
print("disconnecting",user)
clients.get(project_id,[]).pop(user)
async def hello(websocket, path):
project_id = ""
user = ""
async for data in websocket:
print(f"< {user} - {data}")
try:
j = json.loads(data)
if j.get('method','') == 'handshake':
project_id,user = await handshake(websocket,j)
if j.get('method','') == 'set':
await set_variable(j)
finally:
pass
await disconnect(project_id,user)
start_server = websockets.serve(hello, 'localhost', 5000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()