john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

twisted socket bind REUSEADDR shutdown

# http://docs.python.org/2/library/socket.html  , all the way at the bottom

def can_bind_port(port_num):
    """Test if the given port is available to bind to"""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # if restarting services TIME_WAIT isn't important
        s.bind(('localhost', port_num))
        s.shutdown( socket.SHUT_RDWR )  # best practice but doesn't work
        s.close()
    except Exception:
        return False
    else:
        return True



class ClientServerServiceTLS(internet.TCPServer):

    def __init__(self, chat_port, core):
        log.msg('Creating TLS service on port %d' % chat_port)
        internet.TCPServer.__init__(self, chat_port,
                                    ClientFactory(self, core))

    def add_client(self, client):
        return self.parent.add_client(client)

    def remove_client(self, client):
        return self.parent.remove_client(client)



class ClientServerServiceSSL(internet.SSLServer):

    def __init__(self, chat_port, core):
        log.msg('Creating SSL service on port %d' % chat_port)
        cf = ssl.ChainedSSLContextFactory(core.cert_key, core.cert_crt)
        internet.SSLServer.__init__(self, chat_port,
                                    ClientFactory(self, core),
                                    cf)

    def add_client(self, client):
        return self.parent.add_client(client)

    def remove_client(self, client):
        return self.parent.remove_client(client)

  • « Nano
  • Chef modify an existing file »

Published

Sep 19, 2013

Category

python-twisted

~107 words

Tags

  • bind 3
  • python 180
  • reuseaddr 1
  • shutdown 2
  • socket 3
  • twisted 20