Python - while循环结束时它不应该

时间:2016-03-02 02:51:32

标签: python while-loop

Python noob在这里。我正在编写一个简单的客户端/服务器程序,要求用户输入名称,用户名,电子邮件地址和密码。此信息将发送到服务器,服务器检查此用户的文本文件中是否存在条目。如果有,它应该发回一条消息说该用户已经存在,要求用户再试一次。

我将名为flag的变量设置为False。我根据文本文件检查用户信息,如果在文件中找不到匹配项,我将Flag设置为true。然后我有一个if语句,说明如果flag为True,则在文件中写入用户信息。

但是,当我输入重复信息时,它会发回相应的“用户已存在”消息,但无论如何都会将重复信息写入UserProfile.txt文件中。我不断重写我的循环和if语句不同,看看它是否会有所作为,但无论如何,我都遇到了同样的问题。

from socket import *
from datetime import datetime
#Create a welcome socket bound at serverPort
serverPort = 12009
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(10)
print ('The Hello Name server is ready to receive')
accessTime = datetime.now();
print("Access time is", accessTime);
flag = False

while 1:

    while not flag:
        connectionSocket, addr = serverSocket.accept()
        #Wait for the hello message 
        sentence1 = connectionSocket.recv(1024)
        print("From", addr,sentence1.decode('ascii'))
        #Ask for name if a hello message is received
        if(sentence1.decode('ascii').upper() == "HELLO"):
            returnMessage1 = "Please provide the requested information."
        connectionSocket.send(returnMessage1.encode()) 
        #Wait for the name
        sentence2 = connectionSocket.recv(1024)
        fullName = sentence2.decode('ascii')
        #Wait for the email
        sentence3 = connectionSocket.recv(1024)
        email = sentence3.decode('ascii')
        #Wait for the username
        sentence4 = connectionSocket.recv(1024)
        userName = sentence4.decode('ascii')
        #Wait for the password
        sentence5 = connectionSocket.recv(1024)
        password = sentence5.decode('ascii')



        for line in open("UserProfile.txt").readlines():
            if line.find(userName) > -1:    #found the username in this record
                returnMessage3 = "Username already exists, please try again" #reject username
                connectionSocket.send(returnMessage3.encode())
            if line.find(fullName) > -1 and line.find(email) > -1:
                returnMessage4 = "Account already exists for this person, please try again" #reject email                 
            else:
                flag = True

    if flag:            

        #Prepare the access record with information separated by tab key
        userAccount = userName+"\t"+password+"\t"+fullName+"\t"+email+"\n"
        #Append the access record into accessRecord.txt
        output_file = open("UserProfile.txt", "a")
        output_file.write(userAccount)
        output_file.close()
        #Respond the client with the access information
        returnMessage2 = "Registration Successful"
        connectionSocket.send(returnMessage2.encode())

    connectionSocket.close()                #Close the connection

1 个答案:

答案 0 :(得分:1)

当您发现用户名已存在时,您会发回回复,但您不会停止。

尝试在if块中添加break

for line
    if user name in line
        send message about already exists
        break - out of for loop