add demo script using websockets and asyncio
This commit is contained in:
		
							
								
								
									
										5
									
								
								app.py
									
									
									
									
									
										
										
										Normal file → Executable file
									
								
							
							
						
						
									
										5
									
								
								app.py
									
									
									
									
									
										
										
										Normal file → Executable file
									
								
							| @ -1,3 +1,4 @@ | |||||||
|  | #!/usr/bin/env python3 | ||||||
| from flask import Flask, render_template, url_for, request, redirect, Response, abort, session | from flask import Flask, render_template, url_for, request, redirect, Response, abort, session | ||||||
| from flask_sock import Sock | from flask_sock import Sock | ||||||
| from flask_sqlalchemy import SQLAlchemy | from flask_sqlalchemy import SQLAlchemy | ||||||
| @ -28,8 +29,8 @@ def get_date(): | |||||||
|     date = datetime.now() |     date = datetime.now() | ||||||
|     return { "now": date.strftime("%Y-%m-%d") } |     return { "now": date.strftime("%Y-%m-%d") } | ||||||
|  |  | ||||||
| @sock.route('/<namespace>') | @sock.route('/') | ||||||
| def echo(sock,namespace): | def echo(sock): | ||||||
|     while True: |     while True: | ||||||
|         data = json.loads(sock.receive()) |         data = json.loads(sock.receive()) | ||||||
|         sock.send(json.dumps({"method":"set","name":"test","value":"abcd"})) |         sock.send(json.dumps({"method":"set","name":"test","value":"abcd"})) | ||||||
|  | |||||||
| @ -3,13 +3,14 @@ | |||||||
| <div id="data"></div> | <div id="data"></div> | ||||||
| <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script> | <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script> | ||||||
| <script> | <script> | ||||||
|     let socket = new WebSocket("ws://localhost:5000/testProject"); |     let socket = new WebSocket("ws://localhost:5000"); | ||||||
|     let projectID = "1234"; // hier project ID eintragen |     let projectID = "1234"; // hier project ID eintragen | ||||||
|  |  | ||||||
|     function setVariable(name, value) { |     function setVariable(name, value) { | ||||||
|         console.log(`Setting variable: ${name} = ${value}`); |         console.log(`Setting variable: ${name} = ${value}`); | ||||||
|         socket.send(JSON.stringify({ |         socket.send(JSON.stringify({ | ||||||
|             method: "set", |             method: "set", | ||||||
|  |             project_id: projectID, | ||||||
|             name, |             name, | ||||||
|             value |             value | ||||||
|         })); |         })); | ||||||
| @ -21,8 +22,10 @@ | |||||||
|       socket.send(JSON.stringify({ |       socket.send(JSON.stringify({ | ||||||
|         method: "handshake", |         method: "handshake", | ||||||
|         project_id: projectID, |         project_id: projectID, | ||||||
|         user: "testClientHtml" |         user: "testClient"+Math.random() | ||||||
|       })); |       })); | ||||||
|  |  | ||||||
|  |       setInterval(function() { setVariable('test',Math.random()) }, Math.random(3)*1000); | ||||||
|     }; |     }; | ||||||
|  |  | ||||||
|     socket.onmessage = function(event) { |     socket.onmessage = function(event) { | ||||||
|  | |||||||
| @ -3,7 +3,7 @@ | |||||||
| <div id="data"></div> | <div id="data"></div> | ||||||
| <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script> | <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script> | ||||||
| <script> | <script> | ||||||
|     let socket = new WebSocket("ws://localhost:5000/echo"); |     let socket = new WebSocket("ws://localhost:5000/"); | ||||||
|     socket.onopen = function(e) { |     socket.onopen = function(e) { | ||||||
|       console.log("connection established"); |       console.log("connection established"); | ||||||
|       socket.send("Hello World"); |       socket.send("Hello World"); | ||||||
|  | |||||||
							
								
								
									
										42
									
								
								test.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								test.py
									
									
									
									
									
										Normal 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() | ||||||
		Reference in New Issue
	
	Block a user