Python socketserver, how to get my own tcp port number
Question: I need to use socketserver to build a tcp server. According to their document,
I need to inherit the class TCPServer, and pass it a subclass of class
BaseRequestHandler where I rewrite the method handle().

Right now I need to build two server on different port, is there a way that in
handle() function, (otherwise I have to setup two almost identical handler
class, which is not I want), I can get my own port number?


Answer: Don't do it in the `handle()` method, pass the port number in (from this
<https://docs.python.org/2/library/socketserver.html#socketserver-tcpserver-
example>):

    
    
    #!/usr/bin/env python
    
    import SocketServer, argparse
    
    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.server.server_address is a tuple (IP, port) the server is listening on                                                       
            (host, port) = self.server.server_address
            print 'port # is: {}'.format(port)
            # 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__":
        parser = argparse.ArgumentParser()
        parser.add_argument('-p', '--port', required=True, help='the TCP port to listen on')
        args = parser.parse_args()
        HOST, PORT = "localhost", int(args.port)
    
        # 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()
    

In this example, you must provide the port number as an argument when you
start the program using the `-p` command line switch.

