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

问题描述

所以我正在用 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')

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)