websocket part2 | notificação

This commit is contained in:
2025-03-04 22:17:30 -03:00
parent 3a7cbfc413
commit d366d2db97
11 changed files with 195 additions and 91 deletions

View File

@@ -2,70 +2,70 @@ import asyncio
import websockets
import json
import logging
import uuid
# Configure logging
# Configurar o registro de logs
logging.basicConfig(level=logging.INFO)
connected_clients = set() # Keep track of connected clients
connected_clients = set()
async def handle_client(websocket): # Remove 'path' argument
"""Handles a single client connection."""
logging.info(f"Client connected: {websocket.remote_address}")
async def handle_client(websocket):
logging.info(f"Cliente conectado: {websocket.remote_address}")
connected_clients.add(websocket)
# for client in connected_clients:
# await client.send(json.dumps({"message": "Novo cliente conectado"}))
# print(client)
try:
async for message in websocket:
logging.info(f"Received message from {websocket.remote_address}: {message}")
print(f"Received message from {websocket.remote_address}: {message}")
logging.info(f"Mensagem recebida de {websocket.remote_address}: {message}")
print(f"Mensagem recebida de {websocket.remote_address}: {message}")
try:
data = json.loads(message)
# Process the message here
# Processa a mensagem aqui
await process_message(data, websocket)
except json.JSONDecodeError:
logging.error(f"Invalid JSON received from {websocket.remote_address}: {message}")
await websocket.send(json.dumps({"error": "Invalid JSON format"}))
logging.error(f"JSON inválido recebido de {websocket.remote_address}: {message}")
await websocket.send(json.dumps({"error": "Formato JSON inválido"}))
except Exception as e:
logging.error(f"Error processing message from {websocket.remote_address}: {e}")
await websocket.send(json.dumps({"error": "Error processing message"}))
logging.error(f"Erro ao processar mensagem de {websocket.remote_address}: {e}")
await websocket.send(json.dumps({"error": "Erro ao processar mensagem"}))
except websockets.exceptions.ConnectionClosedOK:
logging.info(f"Client disconnected: {websocket.remote_address}")
logging.info(f"Cliente desconectado: {websocket.remote_address}")
except websockets.exceptions.ConnectionClosedError:
logging.error(f"Client connection closed with error {websocket.remote_address}")
logging.error(f"Conexão do cliente fechada com erro {websocket.remote_address}")
except Exception as e:
logging.error(f"Error during connection from {websocket.remote_address} with error {e}")
logging.error(f"Erro durante a conexão de {websocket.remote_address} com erro {e}")
finally:
connected_clients.remove(websocket)
async def process_message(data, websocket):
"""Processes the received message and takes actions."""
# Example: check if it's a broadcast message
if "type" in data and data["type"] == "broadcast" and "message" in data:
await broadcast_message(data)
print("Broadcast message:", data["message"])
print("Mensagem de Broadcast:", data["message"])
elif "type" in data and data["type"] == "echo" and "message" in data:
await websocket.send(json.dumps({"response": data['message']}))
elif "type" in data and data['type'] == "test":
await websocket.send(json.dumps({"response": "test is ok"}))
await websocket.send(json.dumps({"response": "teste está ok"}))
else:
logging.warning(f"Unknown message type or format: {data}")
await websocket.send(json.dumps({"error": "Unknown message type"}))
logging.warning(f"Tipo de mensagem ou formato desconhecido: {data}")
await websocket.send(json.dumps({"error": "Tipo de mensagem desconhecido"}))
async def broadcast_message(data):
"""Broadcasts a message to all connected clients."""
if connected_clients:
logging.info(f"Broadcasting message: {data}")
logging.info(f"Enviando mensagem por broadcast: {data}")
await asyncio.wait([client.send(json.dumps(data)) for client in connected_clients])
else:
logging.info("No clients connected. Message not broadcasted.")
logging.info("Nenhum cliente conectado.")
async def main():
"""Starts the WebSocket server."""
start_server = websockets.serve(handle_client, "localhost", 8765)
logging.info("WebSocket server started on ws://localhost:8765")
start_server = websockets.serve(handle_client, "192.168.1.150", 8765)
logging.info("Servidor WebSocket iniciado em ws://192.168.1.150:8765")
await start_server
await asyncio.Future() # Keep the server running indefinitely
await asyncio.Future() # Mantém o servidor em execução indefinidamente
if __name__ == "__main__":