Add network status/latency info
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
import websockets
|
||||
from PyQt6.QtCore import QThread, pyqtSignal
|
||||
|
||||
@@ -15,6 +16,7 @@ class SyncClientThread(QThread):
|
||||
chat_message = pyqtSignal(str, str, int) # author, text, timestamp
|
||||
system_message = pyqtSignal(str)
|
||||
sync_event = pyqtSignal(dict)
|
||||
latency_updated = pyqtSignal(int) # latency in ms
|
||||
|
||||
def __init__(self, url="ws://localhost:3000/ws"):
|
||||
super().__init__()
|
||||
@@ -22,6 +24,7 @@ class SyncClientThread(QThread):
|
||||
self.ws = None
|
||||
self.loop = None
|
||||
self.running = False
|
||||
self._ping_sent_at = 0
|
||||
|
||||
def run(self):
|
||||
"""Runs strictly within the newly created QThread"""
|
||||
@@ -44,6 +47,19 @@ class SyncClientThread(QThread):
|
||||
json_str = json.dumps(message)
|
||||
asyncio.run_coroutine_threadsafe(self.ws.send(json_str), self.loop)
|
||||
|
||||
async def _ping_loop(self, ws):
|
||||
"""Sends WebSocket protocol-level pings every 5s to measure latency."""
|
||||
while self.running:
|
||||
try:
|
||||
pong = await ws.ping()
|
||||
sent_at = time.time()
|
||||
await asyncio.wait_for(pong, timeout=5)
|
||||
latency_ms = int((time.time() - sent_at) * 1000)
|
||||
self.latency_updated.emit(latency_ms)
|
||||
except Exception:
|
||||
break
|
||||
await asyncio.sleep(5)
|
||||
|
||||
async def _connect_and_listen(self):
|
||||
while self.running:
|
||||
try:
|
||||
@@ -51,6 +67,7 @@ class SyncClientThread(QThread):
|
||||
self.ws = ws
|
||||
self.connected.emit()
|
||||
|
||||
ping_task = asyncio.create_task(self._ping_loop(ws))
|
||||
try:
|
||||
async for message in ws:
|
||||
if not self.running:
|
||||
@@ -58,6 +75,8 @@ class SyncClientThread(QThread):
|
||||
self._handle_message(json.loads(message))
|
||||
except websockets.ConnectionClosed:
|
||||
pass
|
||||
finally:
|
||||
ping_task.cancel()
|
||||
|
||||
except Exception as e:
|
||||
print(f"WebSocket Error: {e}")
|
||||
|
||||
Reference in New Issue
Block a user