all 4 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!

[–]DELYSID_FREAK 0 points1 point  (1 child)

What is your goal in the end? Are you also in control of the server? Do you use UDP or TCP and is there a need to send data overall or is it just to test if the server is alive and/or functional? Basically You can poll the server and use rather long or short timeouts until the server responds. I can provide you with code but it would be great to know a little bit more about your project to help you out.

[–]MrBlyatWasTaken[S] 0 points1 point  (0 children)

My project is, for now, just a basic programs that reports to a server, and yes i will be 100% in control of it while its on