Python TCP Server Accepting Connections and Broadcasting Commands

后端 未结 2 1535
萌比男神i
萌比男神i 2020-12-20 09:22

I\'ve been working on a game using a number of Raspberry Pis, Python, and some buttons/switches. My game requires a central server that issues commands to multiple clients.

2条回答
  •  抹茶落季
    2020-12-20 09:50

    I have a multithread approach here :

    s.listen(10)
        while 1:
            client_socket, addr = s.accept()
            print ('Connected with ' + addr[0] + ':' + str(addr[1]))
            threading.Thread(target=self.handler, args=(client_socket, addr)).start()        
    
    
    def handler(self, client_socket, addr):
        while 1:
            data = client_socket.recv(BUFF)
            print ('Data : ' + repr(data) + "\n")
            data = data.decode("UTF-8")
    

    I strongly recommend you two write a class for Server and Client, for each client create a Client object and connect it to Server, and store each connected Client (its socket and a name for example) to a dictionary as you did, then you want to broadcast a message you can go through all connected Clients in Server and broadcast message you want like this:

    def broadcast(self, client_socket, message):
            for c in self.clients:
                c.send(message.encode("utf-8"))
    

    Update

    Because you have a thread that runs main you need another thread for running server , I suggest you write a start method for server and call it in a thread :

    def start(self):
        # all server starts stuff comes here as define socket 
        self.s.listen(10)
        while 1:
            client_socket, addr = self.s.accept()
            print ('Connected with ' + addr[0] + ':' + str(addr[1]))
            threading.Thread(target=self.handler, args=(client_socket, addr)).start()
    

    now in main section or main file after create server object run the start thread :

    a = server()
    threading.Thread(target=a.start).start()
    

提交回复
热议问题