Python Socket Multiple Clients

后端 未结 5 1584
难免孤独
难免孤独 2020-11-29 22:23

So I am working on an iPhone app that requires a socket to handle multiple clients for online gaming. I have tried Twisted, and with much effort, I have failed to get a bunc

5条回答
  •  粉色の甜心
    2020-11-29 23:18

    Here is the example from the SocketServer documentation which would make an excellent starting point

    import SocketServer
    
    class MyTCPHandler(SocketServer.BaseRequestHandler):
        """
        The RequestHandler class for our server.
    
        It is instantiated once per connection to the server, and must
        override the handle() method to implement communication to the
        client.
        """
    
        def handle(self):
            # self.request is the TCP socket connected to the client
            self.data = self.request.recv(1024).strip()
            print "{} wrote:".format(self.client_address[0])
            print self.data
            # just send back the same data, but upper-cased
            self.request.sendall(self.data.upper())
    
    if __name__ == "__main__":
        HOST, PORT = "localhost", 9999
    
        # Create the server, binding to localhost on port 9999
        server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()
    

    Try it from a terminal like this

    $ telnet localhost 9999
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    Hello
    HELLOConnection closed by foreign host.
    $ telnet localhost 9999
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    Sausage
    SAUSAGEConnection closed by foreign host.
    

    You'll probably need to use A Forking or Threading Mixin too

提交回复
热议问题