Skip to content

Instantly share code, notes, and snippets.

@erichnascimento
Last active March 18, 2025 23:02
Show Gist options
  • Save erichnascimento/c990cfd70dd93b809db26c92f0978a93 to your computer and use it in GitHub Desktop.
Save erichnascimento/c990cfd70dd93b809db26c92f0978a93 to your computer and use it in GitHub Desktop.
Este servidor responde a pings do cliente para medir latência e testar a confiabilidade da conexão.
import asyncio
import websockets
import time
SERVER_IP = "192.168.X.X" # IP da máquina que está rodando o servidor
PORT = 8765 # Porta do servidor WebSocket
URL = f"ws://{SERVER_IP}:{PORT}"
async def monitor_websocket():
while True:
try:
print(f"[+] Conectando ao servidor {URL}...")
async with websockets.connect(URL) as websocket:
print("[✔] Conectado!")
while True:
start_time = time.time()
await websocket.send("ping")
response = await websocket.recv()
latency = (time.time() - start_time) * 1000 # Em milissegundos
print(f"Ping: {latency:.2f}ms")
await asyncio.sleep(1) # Aguarda 1s antes do próximo ping
except (websockets.exceptions.ConnectionClosed, OSError) as e:
print(f"[!] Conexão perdida! Tentando reconectar...")
await asyncio.sleep(3) # Aguarda antes de tentar reconectar
if __name__ == "__main__":
asyncio.run(monitor_websocket())
import asyncio
import websockets
import time
PORT = 8765 # Porta do servidor WebSocket
async def echo(websocket):
try:
async for message in websocket:
await websocket.send(message) # Retorna a mensagem recebida (ping/pong)
except websockets.exceptions.ConnectionClosed:
print("[!] Cliente desconectado")
async def start_server():
print(f"Servidor WebSocket rodando em ws://0.0.0.0:{PORT}")
async with websockets.serve(echo, "0.0.0.0", PORT):
await asyncio.Future() # Mantém o servidor rodando
if __name__ == "__main__":
asyncio.run(start_server())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment