docker: add container websocket in docker-compose

This commit is contained in:
2025-04-27 14:14:32 -03:00
parent d5d136fc5d
commit e33f9e2974
7 changed files with 33 additions and 17 deletions

View File

@@ -15,17 +15,15 @@ import websockets
async def enviar_mensagem(msg):
try:
uri = "ws://192.168.1.150:8765"
uri = "ws://websocket_server:8765"
async with websockets.connect(uri) as websocket:
await websocket.send(msg)
print(f"> Enviado: {msg}")
# print(f"> Enviado: {msg}")
resposta = await websocket.recv()
print(f"< Recebido: {resposta}")
# resposta = await websocket.recv()
# print(f"< Recebido: {resposta}")
except Exception as e:
print(f"Erro ao enviar mensagem: {e}")
print(f"Erro ao enviar mensagem via websocket: {e}")
def somar(consumo:ProductComanda, comanda:Comanda):
@@ -87,7 +85,7 @@ def addProduct(request, product_id, comanda_id):
'speak': f'Novo pedido! {product.name}, para {comanda.name}.'
})
# asyncio.run(enviar_mensagem(msg))
asyncio.run(enviar_mensagem(msg))
consumo = ProductComanda.objects.filter(comanda=comanda_id)
valores = somar(consumo,comanda)

View File

@@ -98,7 +98,6 @@ def addContaCliente(request):
clientId = int(request.POST.get('select-client'))
comanda = Comanda.objects.get(id=comandaId)
client = Client.objects.get(id=clientId)
# client.debt = Decimal(0)
comanda.client = client
comanda.dt_close = timezone.now()
comanda.status = 'FIADO'

View File

@@ -17,13 +17,13 @@ RRB&C - DashBoard
<input id="data-start" name="data-start" oninput="mediaCuisine()" type="date">
<input id="data-end" name="data-end" oninput="mediaCuisine()" type="date">
</div>
<h4 id="30-days">Últimos 30 diAs</h4>
<h4 id="30-days">Últimos 30 dias</h4>
</div>
<div class="grid-container">
<div class="card-resumo">
<div>
<p> Faturament0 </p>
<p> Faturamento </p>
<h2 id="total-pagamentos">Carregando... </h2>
</div>
<img src="{% static 'midia/icons/money-bag.svg' %}" >

View File

@@ -19,11 +19,6 @@ document.addEventListener('DOMContentLoaded', function() {
function verificarCookieNotificacao() {
var iconNotify = document.getElementById('icon-notify');
if (document.cookie.indexOf('notificacao=') === -1) {
@@ -56,7 +51,7 @@ function cookieNotificacao() {
}
}
const websocket = new WebSocket('ws://192.168.1.150:8765');
const websocket = new WebSocket('ws://0.0.0.0:8765');
const nomeUsuario = document.getElementById('user-info').textContent;
websocket.addEventListener('open', (event) => {

View File

@@ -1,74 +0,0 @@
import asyncio
import websockets
import json
import logging
import uuid
# Configurar o registro de logs
logging.basicConfig(level=logging.INFO)
connected_clients = set()
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"Mensagem recebida de {websocket.remote_address}: {message}")
print(f"Mensagem recebida de {websocket.remote_address}: {message}")
try:
data = json.loads(message)
# Processa a mensagem aqui
await process_message(data, websocket)
except json.JSONDecodeError:
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"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"Cliente desconectado: {websocket.remote_address}")
except websockets.exceptions.ConnectionClosedError:
logging.error(f"Conexão do cliente fechada com erro {websocket.remote_address}")
except Exception as 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):
if "type" in data and data["type"] == "broadcast" and "message" in data:
await broadcast_message(data)
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": "teste está ok"}))
else:
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):
if connected_clients:
logging.info(f"Enviando mensagem por broadcast: {data}")
# await asyncio.wait([client.send(json.dumps(data)) for client in connected_clients])
tasks = [asyncio.create_task(client.send(json.dumps(data))) for client in connected_clients]
await asyncio.wait(tasks)
else:
logging.info("Nenhum cliente conectado.")
async def main():
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() # Mantém o servidor em execução indefinidamente
if __name__ == "__main__":
asyncio.run(main())