Java org.eclipse.paho.client.mqttv3.MqttClient 代码实例

・19 分钟阅读

以下是展示如何使用org.eclipse.paho.client.mqttv3.MqttClient的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public void connect()
{
        MemoryPersistence dataStore = new MemoryPersistence();
        try {
        String clientId = newClientId();
                mqttClient = new MqttClient(this.brokerUri,clientId, dataStore);
                mqttClient.setTimeToWait(COMMAND_TIMEOUT);
                TRACE.log(TraceLevel.DEBUG,"Connect: " + brokerUri); //$NON-NLS-1$
                mqttClient.connect(conOpt);
                mqttClient.setCallback(this);
        } catch (MqttException e) {
                e.printStackTrace();
                // TODO:  Log
                System.exit(1);
        }
}
 

实例 2


@Before
public void setUp() throws Exception {
    startServer();
    m_subscriber = new MqttClient("tcp://localhost:1883", "Subscriber", s_subDataStore);
    m_callback = new TestCallback();
    m_subscriber.setCallback(m_callback);
    m_subscriber.connect();
    m_publisher = new MqttClient("tcp://localhost:1883", "Publisher", s_pubDataStore);
    m_publisher.connect();
}
 

实例 3


@Override
public void run() {
    try {
        // Sets up the client and subscribes to topics
        String tmpDir = Environment.getExternalStorageDirectory() + STORAGE_DIRECTORY;
        MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
        mqttClient = new MqttClient(BROKER_URL, CLIENT_NAME, dataStore);
        mqttClient.setCallback(new CustomMqttCallback());
        if (!connect()) {
            callback.onConnected(false);
            return;
        }
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
 

实例 4


@Override
public void setup(String broker, String clientId) throws ProcessingException {
  try {
    MemoryPersistence persistence = new MemoryPersistence();
    m_session = ClientSession.get();
    m_mqttClient = new MqttClient(broker, clientId, persistence);
    m_mqttClient.setCallback(this);
  }
  catch (Exception e) {
    throw new ProcessingException(TEXTS.get("MqttClientCreateException"), e);
  }
}
 

实例 5


/**
 * @category CONNECTION HANDLING
 */
private void init()
{
    if (mqttClient != null) {
        return;
    }
    try
    {
        String prefix = Preferences.getBrokerSecurityType() == Defaults.VALUE_BROKER_SECURITY_NONE ? "tcp" : "ssl";
        String cid = Preferences.getDeviceName(true);
        Log.v(this.toString(), "broker port: " + Preferences.getBrokerPort());
        mqttClient = new MqttClient(prefix + "://" + Preferences.getBrokerHost() + ":" + Preferences.getBrokerPort(), cid , null);
        mqttClient.setCallback(this);
    } catch (MqttException e)
    {
        // something went wrong!
        mqttClient = null;
        changeState(Defaults.State.ServiceBroker.DISCONNECTED);
    }
}
 

实例 6


@Override
public void setup(String broker, String clientId) throws ProcessingException {
  try {
    MemoryPersistence persistence = new MemoryPersistence();
    m_session = ClientSession.get();
    m_mqttClient = new MqttClient(broker, clientId, persistence);
    m_mqttClient.setCallback(this);
  }
  catch (Exception e) {
    throw new ProcessingException(TEXTS.get("MqttClientCreateException"), e);
  }
}
 

实例 7


public MqttGatewayImpl() {
    try {
        //Update Gateway Info
        gatewayInfo.setType(ObjectFactory.getAppProperties().getGatewayType());
        gatewayInfo.setData(new HashMap<String, Object>());
        gatewayInfo.getData().put(MqttGatewayCommon.IP,
                ObjectFactory.getAppProperties().getGatewayMqttHost());
        gatewayInfo.getData().put(MqttGatewayCommon.PORT,
                ObjectFactory.getAppProperties().getGatewayMqttPort());
        gatewayInfo.getData().put(MqttGatewayCommon.TOPIC,
                ObjectFactory.getAppProperties().getGatewayMqttRootTopic());
        mqttClient = new MqttClient(
                "tcp://" + ObjectFactory.getAppProperties().getGatewayMqttHost() + ":"
                        + ObjectFactory.getAppProperties().getGatewayMqttPort(), CLIENT_ID);
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setConnectionTimeout(CONNECTION_TIME_OUT);
        connectOptions.setKeepAliveInterval(KEEP_ALIVE);
        mqttClient.connect(connectOptions);
        mqttCallbackListener = new MqttCallbackListener(mqttClient);
        mqttClient.setCallback(mqttCallbackListener);
        mqttClient.subscribe(ObjectFactory.getAppProperties().getGatewayMqttRootTopic() + "/#");
        _logger.info("MQTT Gateway[{}] connected successfully..", mqttClient.getServerURI());
        gatewayInfo.getData().put(MqttGatewayCommon.CONNECTION_STATUS, "Connected Successfully");
    } catch (MqttException ex) {
        gatewayInfo.getData().put(MqttGatewayCommon.CONNECTION_STATUS, "ERROR: " + ex.getMessage());
        _logger.error(
                "Unable to connect with MQTT broker gateway[{}], Reason Code: {}, Reboot '{}' service once MQTT Broker gateway comes UP!",
                mqttClient.getServerURI(), ex.getReasonCode(), AppProperties.APPLICATION_NAME, ex);
    }
}
 

实例 8


@Override
public void sendMessage(MessageContext messageContext, String targetEPR, OutTransportInfo outTransportInfo) throws AxisFault {
    properties = BaseUtils.getEPRProperties(targetEPR);
    MqttConnectionFactory mqttConnectionFactory = new MqttConnectionFactory(properties);
    MqttClient mqttClient = mqttConnectionFactory.getMqttClient();
    try {
        mqttClient.setCallback(new MqttPublisherCallback());
        mqttClient.connect();
        if(mqttClient.isConnected()){
           MqttTopic mqttTopic = mqttClient.getTopic(mqttConnectionFactory.getTopic());
           MqttMessage mqttMessage = createMqttMessage(messageContext);
           mqttMessage.setRetained(true);
           mqttTopic.publish(mqttMessage);
        }
        mqttClient.disconnect();
    } catch (MqttException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
}
 

实例 9


/**
* Constructs an instance of the sample client wrapper
* @param brokerUrl the url of the server to connect to
* @param clientId the client id to connect with
* @param cleanSession clear state at end of connection or not (durable or non-durable subscriptions)
* @param quietMode whether debug should be printed to standard out
 * @param userName the username to connect with
 * @param password the password for the user
* @throws MqttException
*/
  public Sample(String brokerUrl, String clientId, boolean cleanSession, boolean quietMode, String userName, String password) throws MqttException {
        this.brokerUrl = brokerUrl;
        this.quietMode = quietMode;
        this.clean         = cleanSession;
        this.password = password;
        this.userName = userName;
        //This sample stores in a temporary directory... where messages temporarily
        // stored until the message has been delivered to the server.
        //..a real application ought to store them somewhere
        // where they are not likely to get deleted or tampered with
        String tmpDir = System.getProperty("java.io.tmpdir");
        MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
        try {
                // Construct the connection options object that contains connection parameters
                // such as cleanSession and LWT
        conOpt = new MqttConnectOptions();
        conOpt.setCleanSession(clean);
        if(password != null ) {
          conOpt.setPassword(this.password.toCharArray());
        }
        if(userName != null) {
          conOpt.setUserName(this.userName);
        }
                // Construct an MQTT blocking mode client
        client = new MqttClient(this.brokerUrl,clientId, dataStore);
        // Set this wrapper as the callback handler
        client.setCallback(this);
} catch (MqttException e) {
        e.printStackTrace();
        log("Unable to set up client: "+e.toString());
        System.exit(1);
}
  }
 

实例 10


public MQTTOutputInteraction(OutputConnector connector,String connectionUrl, String clientId) throws MbException{
      super(connector);
      writeServiceTraceEntry(clsName, "MQTTOutputInteraction", "Entry");
      try {
        this.connectionUrl = connectionUrl;
        topicTag.put("Topic", connector.getProperties().get("topicName"));
        topicTag.put("connectionUrl", connectionUrl);                 
        String strTimeout = connector.getProperties().getProperty("responseTimeout", DEFAULT_RESPONSE_TIMEOUT);
        try {
                this.responseTimeout = Integer.parseInt(strTimeout);
        } catch (NumberFormatException e1) {
                getConnector().getConnectorFactory().getContainerServices()
                        .throwMbRecoverableException(e1);
        }
        String clientNameTrun = null;
        if (clientId.length() > 23) {
                clientNameTrun = clientId.substring(clientId.length() - 23);
        } else {
                clientNameTrun = clientId;
        }
        try {
                dataStore = ((MQTTConnectorFactory)getConnector().getConnectorFactory()).getClientPersistence();
                client = new MqttClient(connectionUrl, clientNameTrun, dataStore);
                writeServiceTraceData(clsName, "MQTTOutputInteraction",
                                "Attempting to connect ...");
                client.connect();
                getConnector().writeActivityLog("12063", new String[] { connectionUrl },
                                topicTag);
                writeServiceTraceData(clsName, "MQTTOutputInteraction",
                                "Connected OK.");
        } catch (MqttException e) {
                String msg = connectionUrl + " when connecting " + client.getClientId() + " on initialisation";
                getConnector().writeActivityLog("12067", new String[] {msg}, topicTag);
                getConnector().getConnectorFactory().getContainerServices()
                        .throwMbRecoverableException("12067", new String[] {msg});
        }
        getConnector().writeActivityLog("12063", new String[] {connectionUrl}, topicTag);
} finally {
       writeServiceTraceExit(clsName, "MQTTOutputInteraction", "Exit");
}
  }
 

实例 11


@Override
public void run() {
        try {
                this.setName(WORKER_NAME);
                String tmpDir = System.getProperty("user.dir") + STORAGE_DIRECTORY;
                MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
                connectionOptions = new MqttConnectOptions();
           connectionOptions.setKeepAliveInterval(10);
                mqttClient = new MqttClient(BROKER_URL, CLIENT_NAME, dataStore);
                mqttClient.connect();
        } catch (MqttException e) {
                e.printStackTrace();
        }
}
 

实例 12


/**
 * Sends a string via Mqtt to a Rabbit Mqtt Broker.
 *
 * @param data String to be transmitted to the Mqtt Broker.
 */
public void sendData(String data) {
        Assert.hasText(data, "data must not be empty nor null");
        DefaultMqttPahoClientFactory factory;
        MqttClient client = null;
        factory = new DefaultMqttPahoClientFactory();
        factory.setPassword("guest");
        factory.setUserName("foobar");
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setPayload(data.getBytes());
        try {
                client = factory.getClientInstance("tcp://" + host + ":" + port, "guest");
                client.connect();
                client.publish("xd.mqtt.test", mqttMessage);
                try {
                        Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw new IllegalStateException(e);
                }
                client.disconnect();
                client.close();
        }
        catch (MqttException mqttException) {
                throw new IllegalStateException(mqttException.getMessage());
        }
}
 

实例 13


public static void main(String[] args) {
if(args.length == 2) {
    topic = args[0];
        content = args[1];
}
printConfiguration();
      try {
          MemoryPersistence  persistence = new MemoryPersistence();
          MqttClient         client      = new MqttClient(broker, clientId, persistence);
          MqttConnectOptions opts        = new MqttConnectOptions();
          MqttMessage        message     = new MqttMessage(content.getBytes());
        message.setRetained(retained);
          client.connect(opts);             System.out.println("Connected to broker");                        
          client.publish(topic, message);   System.out.println("Message '"+content+"' published to topic '"+topic+"'");
          client.disconnect();              System.out.println("Disconnected");
          System.exit(0);
      } 
catch(MqttException me) {
          me.printStackTrace();
      }
  }
 

实例 14


public void updateSO_MQTT(String stream_name, String SOID) throws Exception {
        String header = "{"meta": {"authorization": ""+getAPIToken()+"","method": "PUT","url": "/"+SOID+"/streams/"+stream_name+""},";
        String body = ""body": {"lastUpdate": "+System.currentTimeMillis()+","channels": {";
        SO_channel tempChannel;
        for(int i=0;i<list.size()-1;i++) {
                tempChannel = list.get(i);
                body+="""+tempChannel.getName()+"": {"current-value": ""+tempChannel.getValue()+""},";
        }
        tempChannel = list.get(list.size()-1);
        body += """+tempChannel.getName()+"": {"current-value": ""+tempChannel.getValue()+""}}}}";
        String message = header+""+body;
        MemoryPersistence mMemStore = new MemoryPersistence();
        MqttConnectOptions opt = new MqttConnectOptions();
        MqttClient mClient = new MqttClient("tcp://"+this.mqtt_server_url+":"+this.mqtt_server_port, ""+getDeviceID(),mMemStore);
        if(mqtt_username.length()>0 && mqtt_password.length()>0) {
        opt.setUserName(mqtt_username);
        opt.setPassword(mqtt_password.toCharArray());
        mClient.connect(opt);
        }else {
                mClient.connect();
        }
        MqttMessage mq_message = new MqttMessage();
        mq_message.setPayload(message.getBytes());
        mClient.publish(getAPIToken()+"/from", mq_message);
        mClient.disconnect();
}
 

实例 15


@Activate
void activate() throws Exception {
        try {
                URI tcpUri = new URI("tcp", null, boundUri.getHost(), boundUri.getPort(), null, null, null);
                client = new MqttClient(tcpUri.toString(), clientId);
                client.connect();
        } catch (Exception e) {
                e.printStackTrace();
        }
}
 
讨论
淘淘あ西西 profile image