Skip to content

Instantly share code, notes, and snippets.

@jkerhin
Last active July 16, 2025 01:47
Show Gist options
  • Select an option

  • Save jkerhin/776d0f92b8d27532d516be07f47b947d to your computer and use it in GitHub Desktop.

Select an option

Save jkerhin/776d0f92b8d27532d516be07f47b947d to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import logging
import socket
import time
HOST = "localhost"
PORT = 8675
MAX_CONNECTIONS = 10
TIMEOUT_S = 2.0
SLEEP_S = 1.0
def try_to_read(n):
try:
sock = socket.create_connection((HOST, PORT), timeout=TIMEOUT_S)
logging.info("Socket %d - Successful connection", n)
except ConnectionRefusedError as err:
logging.error("Socket %d - Connection refused %s", n, err)
return False
try:
data = sock.recv(10)
except TimeoutError:
logging.info("Socket %d - Timeout after blocking for %f seconds", n, TIMEOUT_S)
return True
if len(data) > 0:
logging.info("Socket %d - Successfully read data %s", n, data.hex())
return True
else:
logging.info("Socket %d - Immediate return reading 0 bytes", n)
return False
def main():
logging.info("Running")
for n in range(1, MAX_CONNECTIONS + 2):
status = try_to_read(n)
status_str = "Success!" if status else "Failure"
logging.info("Socket %d - %s", n, status_str)
time.sleep(SLEEP_S)
if __name__ == "__main__":
logging.basicConfig(
format="%(asctime)s [%(levelname)s]: %(message)s", level=logging.INFO
)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment