0
votes

I am writing a service discovery application which will register web applications on a zookeeper node. One of the attribute is the port number on which service is available. In code I got the handle of jetty server instance but how can I find the port number from a Jetty Server instance ?

1

1 Answers

0
votes

Walk the connectors, and ask them for their registered host names (so you know what network interfaces they are listening on) and local ports (that they are bound to).

Here's a template you can start with.

    for (Connector connector : server.getConnectors())
    {
        if (connector instanceof NetworkConnector)
        {
            // we have a network capable connector
            NetworkConnector networkConnector = (NetworkConnector) connector;
            // What interface?
            String interfaceName = networkConnector.getHost();
            // What local port is it bound to?
            int localPort = networkConnector.getLocalPort();
            // What is the declared protocol default for this connector?
            String defaultProtocol = networkConnector.getDefaultConnectionFactory().getProtocol();
            // What other features does this connector handle?
            for (ConnectionFactory connectionFactory : networkConnector.getConnectionFactories())
            {
                // List of protocols handled by this specific connection factory for this specific connector
                connectionFactory.getProtocols();

                if (connectionFactory instanceof SslConnectionFactory)
                {
                    // this can handle TLS/SSL based connections
                }

                if (connectionFactory instanceof HttpConnectionFactory)
                {
                    // this can handle http protocols

                    // get the http specific configuration
                    HttpConfiguration httpConfig = ((HttpConnectionFactory) connectionFactory).getHttpConfiguration();
                    // what port is recognized as secure
                    httpConfig.getSecurePort();
                    // what scheme is recognized as secure
                    httpConfig.getSecureScheme();
                }

                if (connectionFactory instanceof HTTP2ServerConnectionFactory)
                {
                    // can handle encrypted http/2 protocols (and alpn features)
                }

                if (connectionFactory instanceof HTTP2CServerConnectionFactory)
                {
                    // this can handle http/2's special clear-text "h2c" protocol (no alpn features)
                }
            }
        }
    }