Python socketserver,如何获取自己的tcp端口号

时间:2015-11-09 22:23:18

标签: python tcp

我需要使用socketserver来构建tcp服务器。根据他们的文档,我需要继承类TCPServer,并将它传递给类BaseRequestHandler的子类,我在其中重写方法handle()。

现在我需要在不同的端口上构建两个服务器,有没有一种方法在handle()函数中,(否则我必须设置两个几乎相同的处理程序类,这不是我想要的),我可以得到我自己的端口号?

2 个答案:

答案 0 :(得分:1)

不要在handle()方法中执行此操作,传递端口号(来自此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()

在此示例中,使用-p命令行开关启动程序时,必须提供端口号作为参数。

答案 1 :(得分:0)

我刚刚发现一个解决方案可能符合条件,但它仍然不够好,因为我仍然需要更改代码中的两个端口才能使其工作:

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()