程序不断地出奇怪的结果

2024-05-14 12:04:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我的程序,我的服务器接收的数据,我不是从我的客户端发送

Connection from: ('192.168.0.17', 58167)
data recieved : __UserLogin123__
User Login requested
James Green at recieve login
James Green in accessCodes
93
{93: ['James', 'Green']}
Found
User Found
3
data recieved : __QUIT____CHECK_SCORE__
Incorrect code received
done
Connection from: ('192.168.0.17', 58182)
data recieved : __UserLogin123__
User Login requested
James Green at recieve login
James Green in accessCodes
93
{93: ['James', 'Green']}
Found
User Found
3
data recieved : __QUIT____CHECK_SCORE__
Incorrect code received

最后一个“data received:QUIT\uuuuu CHECK\u SCORE完全没有意义,我使用代码访问类中的方法,这些类将发送特定类型的数据,告诉服务器我是否要(例如)将用户添加到数据库中,它通过访问一个用字符串键存储方法的字典来实现。 这是我客户的“handler”和“main”:

def Main():
    global s
    host = "192.168.0.17"
    port = 5000
    ID = "__UserLogin123__"

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.connect((host, port))
    s.send(str.encode(ID))
    setupCheck = s.recv(2048).decode()
    time.sleep(1)
    if setupCheck == "__dataReceived__":
        username = input("Enter username : ")
        password = input("Enter password : ")
        userDetails = (username, password)
        dataString = pickle.dumps(userDetails)
        s.send(dataString)

    access = s.recv(2048).decode()
    print(access)
    if access == "__ACCESS_GRANTED__":
        permissionLvl = s.recv(2048).decode()
        print(permissionLvl)
        if permissionLvl == "1":
            ClientUser = User(username,password)
        elif permissionLvl == "2":
            ClientUser = Admin(username,password)
        elif permissionLvl == "3":
            ClientUser = HeadAdmin(username,password)
        else:
            print("SOMETHING WRONG SOMETHING WROGN")
            time.sleep(3)
        handler(ClientUser)
    else:
        print("Incorrect details provided")


def handler(ClientUser):
    function_dict = {"__QUIT__": ClientUser.quit(), "__PLAY_GAME__":         ClientUser.playGame(),
                 "__CHECK_SCORE__": ClientUser.checkScore(),"__CHECK_USERS__": ClientUser.checkUsers(),
                 "__ADD_ASSIGNMENT__": ClientUser.addAssignment(),"__REMOVE_ASSIGNMENT__": ClientUser.removeAssignment(),
                 "__EDIT_ASSIGNMENT__": ClientUser.editAssignment(), "__ADD_USER__": ClientUser.addUser(),
                 "__EDIT_USER__": ClientUser.editUser(), "__REMOVE_USER__": ClientUser.removeUser(),
                 "__CREATE_GROUP__": ClientUser.createGroup()}

    while True:
        checkDataReady = s.recv(2048).decode()
        print(checkDataReady)
        if checkDataReady == "__dataExchangeReady__":
            print("Available Commands:")
            ClientUser.availableCommands()
            commandChoice = ""

            while commandChoice not in choices:
                while True:
                    try:
                        commandChoice = int(input("Please enter your choice (number) \n-> "))
                    except ValueError:
                        print("Please only enter integers")
                    finally:
                        if commandChoice > 14 or commandChoice < 0:
                            print("Please only enter one of the numbers listed")
                        else:
                            break

                commandChoice = choices[commandChoice]
                print(commandChoice)
                checkString = "Are you sure you want to : " + commandChoice + "? (Y/N) -> "
                check = input(checkString)
                if check.upper() == "N":
                    commandChoice = ""
            print("executing function")
            function_dict[commandChoice]

下面是一些服务器端代码,我认为与问题有关:

def handler(conn, addr):
    print("done")
    print("Connection from: " + str(addr))
    dbSetup()
    while True:
        time.sleep(1)
        data = conn.recv(2048).decode()
        print("data recieved : " + data)
        if data == "__QUIT__" or not data:
            print("Connection closed")
            print("Connection Closed by",  addr[0], ":", addr[1])
            break
        elif data in accessCodes:
            accessCodesHandler(data)
        elif data in commandCodes:
            commandCodesHandler(data)
        else:
            print("Incorrect code received")
            break
        conn.send(str.encode("__dataExchangeReady__"))

    conn.close()

def accessCodesHandler(accessCode):
    if accessCode == accessCodes[0]:
        print("User Login requested")
        username, password = receiveLoginDetails()
        print(username,password, "in accessCodes")
        userCheck = getUser_InHash(username, password)
        if userCheck == True:
            userPermissionLvl = str(getUser_InUserDb(username,"")[2])
            print("User Found")
            conn.send(str.encode("__ACCESS_GRANTED__"))
            time.sleep(1)
            print(userPermissionLvl)
            conn.send(str.encode(userPermissionLvl))

        else:
            print("User not found")
            conn.send(str.encode("__AccessDenied__"))
    else:
        print("Head admin setup protocol executed")
        username, password = receiveLoginDetails()
        addUser_InHash(username, password, 3)

我看不出为什么我的服务器会输出“QUIT\u CHECK\u SCORE”,因为我没有发送任何明确表示客户端错误代码的数据:

Enter username : James
Enter password : Green
__ACCESS_GRANTED__
3
James
Green
Traceback (most recent call last):
  File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 197, in <module>
Main()
  File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 153, in Main
handler(ClientUser)
  File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 161, in handler
"__ADD_ASSIGNMENT__": ClientUser.addAssignment(),"__REMOVE_ASSIGNMENT__":     ClientUser.removeAssignment(),
  File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 37, in removeAssignment
    s.send(str.encode("__REMOVE_ASSIGNMENT__"))
ConnectionResetError: [WinError 10054] An existing connection was forcibly         closed by the remote host

Process finished with exit code 1 

对不起,如果这是不够的信息,我真的不知道什么是错误的程序。提前谢谢你的帮助


Tags: insenddataifusernamegreenpasswordconn
1条回答
网友
1楼 · 发布于 2024-05-14 12:04:16

你的字典初始化代码可疑。你知道吗

下面实际调用funca()并将其返回值存储为与键“a”关联的值:

d = { 'a': funca() }

如果要存储funca函数本身,以便以后查找和调用,请使用:

d = { 'a': funca }

相关问题 更多 >

    热门问题