Search code examples
pythonsocketsportsocketserver

python SocketServer.BaseRequestHandler knowing the port and use the port already opened


This is the code which i played, but each time i make a mistake i can't relaunch it. It says to me that the port / socket is already used That's the first question The second one is in my MyTCPHandler how can i kno the port used ? here is my code :

# MetaProject v 0.2
# -*- coding: utf-8 -*-
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow :
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam
"""
import SocketServer
import threading

class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024)
        socket = self.request
        print "%s wrote:" % self.client_address[0]
        print self.data
        print self.__dict__
        socket.sendto(self.data.upper(), self.client_address)

def serve_thread(host, port):
    server = SocketServer.TCPServer((host, port), MyTCPHandler)
    server.serve_forever()

if __name__ == "__main__":
    threading.Thread(target=serve_thread,args=('localhost', 1238)).start()
    threading.Thread(target=serve_thread,args=('localhost', 1237)).start()
    print "toto"

i've made :

def serve_thread(host, port):
    if port == 1858 :
        server = SocketServer.TCPServer((host, port), Serverhttp,bind_and_activate=True)
    elif port == 1958 :
        server = SocketServer.TCPServer((host, port), Serversmtp,bind_and_activate=True)
    server.allow_reuse_address=True
    server.serve_forever()

but it doesn't work. Regards


Solution

  • Create your SocketServer with bind_and_activate=True in the call to the constructor.

    Then set server.allow_reuse_address=True.

    If you want to differentiate between the two ports, you can use two different classes for the request handlers.

    Edit:

    Modify your code to look like:

    def serve_thread(host, port):
        if port == 1858 :
            server = SocketServer.TCPServer((host, port), Serverhttp,bind_and_activate=True)
        elif port == 1958 :
            server = SocketServer.TCPServer((host, port), Serversmtp,bind_and_activate=True)
        server.allow_reuse_address=True
        server.server_bind()
        server.server_activate()
        server.serve_forever()
    

    It might be cleaner to create your own server class. Something like this:

    class ReuseAddrServer(SocketServer.TCPServer):
        def __init__(self, (host, port)):
            SocketServer.TCPServer.__init__(self, (host, port), bind_and_activate=False)
            self.allow_reuse_address = True
            self.server_bind()
            self.server_activate()