From d5f0b09fbab5b67c46df5a51220e84fabc0c3097 Mon Sep 17 00:00:00 2001 From: arne <arne@br0tkasten.de> Date: Sun, 29 Jan 2023 13:16:41 +0100 Subject: [PATCH] add demo script using websockets and asyncio --- app.py | 5 +++-- docs/client.html | 7 +++++-- docs/echo.html | 2 +- test.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 5 deletions(-) mode change 100644 => 100755 app.py create mode 100644 test.py diff --git a/app.py b/app.py old mode 100644 new mode 100755 index b7ba735..b5d5ddf --- a/app.py +++ b/app.py @@ -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"})) diff --git a/docs/client.html b/docs/client.html index 56d430c..7208036 100644 --- a/docs/client.html +++ b/docs/client.html @@ -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) { diff --git a/docs/echo.html b/docs/echo.html index 5da125e..b0c20d4 100644 --- a/docs/echo.html +++ b/docs/echo.html @@ -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"); diff --git a/test.py b/test.py new file mode 100644 index 0000000..3a0c63c --- /dev/null +++ b/test.py @@ -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() \ No newline at end of file