1

所以我目前正在为一个小游戏编写一个python服务器。我目前正在尝试让程序在线程中运行两个服务器。通过测试,我发现我的过程中有一个小问题,那就是一次只有一个服务器在运行。我为每台服务器使用不同的端口,但是首先连接的端口占主导地位。服务器代码片段:

class loginServer(socketserver.BaseRequestHandler):

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        sent = str(self.data,'ascii').split(":")
        print("login:\t\t",sent)
        if (sent[0] == "l"):
            #login check
            #cur.execute("SELECT password, userid FROM `prototb` WHERE username = '"+sent[1]+"'")
            cur.execute("SELECT `displayname`,`curmap`,`curpos`,`Inventory`,`abilities`,`password`,`userid` FROM `prototb` WHERE username = '"+sent[1]+"'")            
            plyInfo = cur.fetchone()#get the information from the database
            if (plyInfo != None):#if the account doesnt exist the username is wrong
                if (plyInfo[5] == sent[2]):#check the correctness of the password
                    print("Login-Success:\t",plyInfo)
                    send = pickle.dumps([plyInfo[1],plyInfo[2],plyInfo[3],plyInfo[4],plyInfo[5]])
                else:
                    self.request.send(bytes("-", 'ascii'))#refuse entry (bad password)
            else:
                self.request.send(bytes("-", 'ascii'))#refuse entry (bad username)

def run_loginServer():
    HOST, PORT = "localhost", 9000

    # Create the server, binding to localhost on port 9000
    server = socketserver.TCPServer((HOST, PORT), loginServer)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

对于另一个服务器线程:

class podListener(socketserver.BaseRequestHandler):

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        sent = str(self.data,'ascii').split(":")
        print("pods:\t\t",sent)
        if (sent[0] == "l"):
            maps[mapNum][0] = sent[1]
            maps[mapNum][1] = self.client_address[0]
            maps[mapNum][2] = sent[2]
            print("Pod Connected:\t",maps[mapNum])
            #send confirmation
            self.request.send(bytes("+", 'ascii'))
        else:
            print("Pod Failed connection: ", self.client_address[0])


def run_podListener():
    HOST, PORT = "localhost", 9001

    # Create the server, binding to localhost on port 9001
    server = socketserver.TCPServer((HOST, PORT), podListener)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

然后我运行它来启动它们:

if __name__ == "__main__":
    #get the database handle
    run_dbConnect()
    #run the map pod server
    run_podLauncher()
    #run the login server ### localhost 9000
    run_loginServer()

当我单独注释掉线程但从不一起注释时,客户端分别连接到它们。任何帮助将不胜感激。

4

0 回答 0