程序不断推出奇怪的结果

时间:2018-09-03 20:18:33

标签: python class sockets dictionary methods

我的程序出现问题,我的服务器接收到我不是从客户端发送的数据

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

最后一个“接收到的数据: QUIT ___ CHECK_SCORE ”完全没有意义,我使用代码访问类中的方法,这些类将发送某些类型的数据告诉服务器是否要添加(例如)用户访问数据库,并通过访问带有字符串键的存储方法的字典来实现。 这是我客户的“处理程序”和“主要”:

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__CHECK_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 

很抱歉,如果此信息不足,我真的不知道该程序出了什么问题。预先感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您的字典初始化代码可疑。

以下代码实际上调用funca()并将其返回值存储为与键'a'关联的值:

import tensorflow as tf
x = tf.placeholder(tf.float32, shape=[1], name='x')
y = tf.add(x, 1.0)
feed = dict()
feed[x] = 0.0
with tf.Session() as sess:
    print('Simple:', sess.run(y, feed_dict=feed))

# ValueError: Cannot feed value of shape () for Tensor 'x:0', which has shape '(1,)'

如果您想存储d = { 'a': funca() } 函数本身,以供以后查找和调用,请使用:

funca