错误的 python asyncio 套接字授权

问题描述 投票:0回答:1

使用 asyncio(套接字)编写身份验证: 服务器:

       is_authenticated = False

        while not is_authenticated:
            writer.write(b'Enter username: ')
            await writer.drain()
            username = (await reader.read(256)).decode()
            writer.write(b'Enter password: ')
            await writer.drain()
            password = (await reader.read(256)).decode()
            print(f'Username: {username}, Password: {password}')

            if bool(self.db.is_client_exists(username, password)):
                is_authenticated = True
                writer.write(b'Successfully authenticated')
            else:
                writer.write(b'Authentication failed. Please try again.')

客户:

async def authenticate(reader: StreamReader, writer: StreamWriter):
    result = ''
    while result != 'Successfully authenticated':
        data = await reader.read(256)
        print(data.decode())
        writer.write(input().encode())
        await writer.drain()
        data = await reader.read(256)
        print(data.decode())
        writer.write(input().encode())
        await writer.drain()
        result = (await reader.read(256)).decode()

        if result == 'Successfully authenticated':
            print('You are authenticated!')
        else:
            print('Username or password incorrect. Please try again.')

`
        else:
            print('Username or password incorrect. Please try again.')

第一次错误尝试后客户端无法第二次登录(服务器不应答)。在调试模式下一切正常。有什么错误

我尝试将 aioconsole 与异步输入一起使用,但它不起作用

python sockets asynchronous python-asyncio
1个回答
0
投票

在您的服务器代码中,您期望客户端首先发送用户名,然后发送密码。但是,在您的客户端代码中,您同时发送用户名和密码。

修改您的客户端代码:

from asyncio import StreamWriter, StreamReader

async def authenticate(reader: StreamReader, writer: StreamWriter):
    result = ''
    while result != 'Successfully authenticated':
        # Send username
        writer.write(input('Enter username: ').encode())
        await writer.drain()
        
        # Send password
        writer.write(input('Enter password: ').encode())
        await writer.drain()

        # Receive authentication result
        result = (await reader.read(256)).decode()

        if result == 'Successfully authenticated':
            print('You are authenticated!')
        else:
            print('Username or password incorrect. Please try again.')

现在,客户端将分别提示用户输入用户名和密码,并将其一次发送到服务器。

确保服务器期望这种消息顺序并相应地处理它们。另外,请确保服务器针对其期望的每个输入向客户端发送正确的提示。如果仍然存在问题,请考虑添加更多调试语句或检查通信过程中可能出现的异常。

© www.soinside.com 2019 - 2024. All rights reserved.