Implement binary message sending
This commit is contained in:
29
main.py
29
main.py
@@ -7,6 +7,7 @@ from dataclasses import dataclass
|
||||
import json
|
||||
import httpx
|
||||
import asyncio
|
||||
import struct
|
||||
|
||||
# Some useful variables
|
||||
PEEHAITCHPEA_ENDPOINT = "http://localhost:9000/api.php?cmd=getselectedmessage"
|
||||
@@ -25,6 +26,7 @@ app.state.auto_polling = False
|
||||
app.state.polling_rate = 5
|
||||
|
||||
# Store for connected websocket clients
|
||||
|
||||
class ConnectionManager:
|
||||
def __init__(self):
|
||||
self.active_connections: List[WebSocket] = []
|
||||
@@ -41,6 +43,29 @@ class ConnectionManager:
|
||||
async def broadcast(self, message: str):
|
||||
for connection in self.active_connections:
|
||||
await connection.send_text(message)
|
||||
|
||||
async def broadcast_binary(self, data_dict: dict):
|
||||
"""
|
||||
Broadcasts a message to all connections as binary data.
|
||||
"""
|
||||
if not self.active_connections:
|
||||
return
|
||||
|
||||
json_str = json.dumps(data_dict)
|
||||
json_bytes = json_str.encode('utf-8')
|
||||
json_length = len(json_bytes)
|
||||
|
||||
# 4-byte unsigned integer (uint32)
|
||||
length_bytes = struct.pack('!I', json_length)
|
||||
|
||||
message_bytes = length_bytes + json_bytes
|
||||
|
||||
for connection in self.active_connections:
|
||||
try:
|
||||
await connection.send_bytes(message_bytes)
|
||||
logger.debug(f"Sent binary message ({json_length} bytes) to a client")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send binary message: {str(e)}")
|
||||
|
||||
manager = ConnectionManager()
|
||||
|
||||
@@ -126,7 +151,7 @@ async def process_subtitles(request: Request, sub_type: str):
|
||||
logger.info(f"Received subtitle text: {subtitle_text}, request type: {sub_type}")
|
||||
|
||||
if manager.active_connections:
|
||||
await manager.broadcast(json.dumps({"type": f"subtitle_{sub_type}", "text": subtitle_text}))
|
||||
await manager.broadcast_binary({"type": f"subtitle_{sub_type}", "text": subtitle_text})
|
||||
|
||||
return JSONResponse(
|
||||
status_code=200,
|
||||
@@ -167,7 +192,7 @@ async def process_selected_message(message: str):
|
||||
"""
|
||||
logger.info(f"Processing message: {message}")
|
||||
if manager.active_connections:
|
||||
await manager.broadcast(json.dumps({"type": "selectedmessage", "message": message}))
|
||||
await manager.broadcast_binary({"type": "selectedmessage", "message": message})
|
||||
|
||||
async def periodic_message_check():
|
||||
"""Periodically checks for new messages."""
|
||||
|
Reference in New Issue
Block a user