3

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Let's say the two handle function are doing almost exactly the same thing, except if the port is 9999 then print 9999, if port is 9998, then print 9998. Does that mean I have to setup two handler class?
See the updated example above. I can get 2 listeners going using the same code (one on port 9998 and one on port 9999) like this: ./sockserv.py -p 9998 & (run the first server, put in the background) and then this: ./sockserv.py -p 9999 & (another server, different port #, put in background)
thank you, but my question is exactly how to pass the PORT number to the function handle(), since my two handle function is almost identical but different based on the port number
I made another change - the handler now prints out the port it got passed. Please try it out.
Hooray! I was afraid we were misunderstanding each other, glad we got it sorted out.
0

I just found out a solution might be eligible, but it's still not good enough since I still have to change two port in the code to make this work:

import socket
import threading
import SocketServer


class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    port = None
    def handle(self):
        while True:
            data = self.request.recv(1024)
            if not data:
                break
        print self.port,data

class ThreadedTCPRequestHandler1(ThreadedTCPRequestHandler):
    port = 9999

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass        

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler1)
    ip, port = server.server_address

    server_thread = threading.Thread(target=server.serve_forever)

    server_thread.daemon = True
    server_thread.start()
    #print "Server loop running in thread:", server_thread.name
    try:
        while True:
            continue
    finally:
        print 'quitting server'
        server.shutdown()
        server.server_close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.