Java Paho MQTT客户端本地地址和端口

Java Paho MQTT客户端本地地址和端口,java,mqtt,paho,Java,Mqtt,Paho,我的问题很简单。 我想知道如何修复客户端的端口 根据Eclipse文档和IBM的,用户必须修复代理地址(这是绝对自然的)。但并没有提到如何修复客户端站点端口的方法。 MQTT也必须在TCP层上,所以我认为可以修复端口 如果你有什么想法,请告诉我。 谢谢,您不需要指定客户端的端口,因为它是由操作系统选择的,就像任何客户端到服务器的连接一样,就像您也不需要使用HTTP连接那样。 以tcp://:的形式在传递的URL中指定MQTT代理的IP地址和端口,例如tcp://localhost:4922 下

我的问题很简单。 我想知道如何修复客户端的端口

根据Eclipse文档和IBM的,用户必须修复代理地址(这是绝对自然的)。但并没有提到如何修复客户端站点端口的方法。

MQTT也必须在TCP层上,所以我认为可以修复端口

如果你有什么想法,请告诉我。 谢谢,您不需要指定客户端的端口,因为它是由操作系统选择的,就像任何客户端到服务器的连接一样,就像您也不需要使用HTTP连接那样。

tcp://:
的形式在传递的URL中指定MQTT代理的IP地址和端口,例如
tcp://localhost:4922

下面的代码显示了如何在OSGi上下文中连接Paho客户机,其中所有连接参数都是从bundle上下文中检索的

private void configureMqtt(BundleContext context) throws IOException, MqttException {
    String broker = context.getProperty("mqtt.broker");

    if (broker == null) {
        throw new ServiceException("Define mqtt.broker");
    }

    String client = context.getProperty("mqtt.clientname");

    if (client == null) {
        throw new ServiceException("Define mqtt.clientname");
    }

    String dir = context.getProperty("mqtt.persistence");

    if (dir == null) {
        dir = "mqtt";
    };

    File directory = context.getDataFile(dir);
    directory.mkdirs();

    logger.config(() -> String.format("MQTT broker: %s, clientname: %s persistence: %s", broker, client, directory.getAbsolutePath()));
    connectOptions = new MqttConnectOptions();
    connectOptions.setWill(GARAGE + "/door", new byte[0], 0, true);

    String ka = context.getProperty("mqtt.keepalive");
    if (ka != null) {
        connectOptions.setKeepAliveInterval(Integer.valueOf(ka));
    }

    persistence = new MqttDefaultFilePersistence(directory.getCanonicalPath());
    mqttClient = new MqttAsyncClient(broker, client, persistence);
    mqttClient.setCallback(this);
    connect();
}

private void connect() {
    logger.fine("Connecting to MQTT broker");

    try {
        IMqttToken token = mqttClient.connect(connectOptions);

        IMqttActionListener listener = new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                logger.log(Level.INFO, "Connected to MQTT broker");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                logger.log(Level.WARNING, "Could not connect to MQTT broker, retrying in 3 seconds", exception);
                service.schedule(this::connect, 3, TimeUnit.SECONDS);
            }
        };

        token.setActionCallback(listener);
    } catch (MqttException e) {
        logger.log(Level.SEVERE, "Cannot reconnect to MQTT broker, giving up", e);
    }
}

在正常情况下,不为TCP连接设置源端口,只让操作系统选择一个随机空闲端口

如果您修复了源端口,那么在给定的机器上一次只能运行一个客户端实例,并且如果出现连接故障,您必须等待TCP堆栈再次释放该套接字,然后才能重新连接


如果出于某种原因,确实需要修复源端口,那么您可能可以编写一个自定义实现,对源端口进行硬编码。然后将其作为对象的一部分传入,但我还是很难找到一个好主意的原因。

为什么要修复客户端的源端口,您想解决什么问题?