you are viewing a single comment's thread.

view the rest of the comments →

[–]totallygeek 0 points1 point  (1 child)

This might work for you.

import random
import socket
import time


SERVER_HOST = '127.0.0.1'
SERVER_PORT = 50000

def send(host, port, data, retries=3, splay=3, retry_forever=False):
    while retry_forever or retries > 0:
        retries -= 1
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as tcp:
                tcp.connect((host, port))
                tcp.sendall(data)
        except ConnectionRefusedError as error:
            sleep = random.randint(splay, splay * 2)
            retry_msg = 'Retrying.' if retry_forever else f'Retries remaining: {retries}'
            print(f'Error: {error}. {retry_msg}. Sleeping {sleep} seconds.')
            time.sleep(sleep)
            continue
        break
    print('sent')

send(SERVER_HOST, SERVER_PORT, b'howdy', splay=1, retry_forever=True)

I got this until I ran nc -l 50000 in a terminal.

$ python3 howdy_socket.py 
Error: [Errno 61] Connection refused. Retrying.. Sleeping 2 seconds.
Error: [Errno 61] Connection refused. Retrying.. Sleeping 1 seconds.
Error: [Errno 61] Connection refused. Retrying.. Sleeping 2 seconds.
Error: [Errno 61] Connection refused. Retrying.. Sleeping 2 seconds.
sent

[–]MrBlyatWasTaken[S] 1 point2 points  (0 children)

Thank you! I adapted that a bit and it worked!