python socket,客户端没有按顺序接收数据

时间:2021-04-03 09:51:47

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

所以我正在用 python 编写一个基于 TCP 的代码,它从客户端发送 2 个变量(用户名和密码),服务器接收这 2 个变量,并基于这些变量,它做了一些事情,但我的问题是我的客户端没有t 接收第二个变量!

客户端代码:

# Variables
ip = "127.0.0.1"
port = 6767
username = "User"
password = "1234

# Connect To Server
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((ip, port))

# Send Information to Server
information_message = client.recv(1024).decode('ascii')
while True:
    if information_message == 'PASSWORD':
        client.send(password.encode('ascii'))
        print(information_message)
    if information_message == 'USERNAME':
        client.send(username.encode('ascii'))
        print(information_message)
    break 

服务器代码:

import socket

# Connection Data
host = '127.0.0.1'
port = 6767

# Starting Server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()

# receive information to client
while True:
    client, address = server.accept()
    client.send('PASSWORD'.encode('ascii'))
    password = client.recv(10240).decode('ascii')
    client.send('USERNAME'.encode())
    username = client.recv(10240).decode('ascii')
    print(username, password)
    break

期待 server.py:

user 1234

server.py 上的真实输出:

Traceback (most recent call last):
  File "C:\Users\Administrator\PycharmProjects\test\server.py", line 29, in <module>
    username = client.recv(10240).decode('ascii')
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

我知道只有 ('PASSWORD') 会作为数据发送给客户端,但我不明白为什么它不会发送第二个数据 ('USERNAME')

1 个答案:

答案 0 :(得分:0)

information_message = client.recv(1024).decode('ascii')
while True:
    if information_message == 'PASSWORD':
        client.send(password.encode('ascii'))
        print(information_message)
    if information_message == 'USERNAME':
        client.send(username.encode('ascii'))
        print(information_message)
    break 

最后一个 break 语句使您的客户端在处理第一个 information_message 后立即退出循环,即在 PASSWORD 之后。在服务器将 USERNAME 写入套接字的那一刻,该套接字已被客户端关闭。虽然 send 可能仍然成功(它也可能因 Broken Pipe 而失败),但由于套接字已关闭,以下 recv 将失败。

您可能想要做的是这样的:

while True:
    try:
        information_message = client.recv(1024).decode('ascii')
    except:
        break

    if information_message == 'PASSWORD':
        client.send(password.encode('ascii'))
        print(information_message)
    if information_message == 'USERNAME':
        client.send(username.encode('ascii'))
        print(information_message)