当前位置: 首页>>代码示例>>Java>>正文


Java MqttConnectOptions.setSocketFactory方法代码示例

本文整理汇总了Java中org.eclipse.paho.client.mqttv3.MqttConnectOptions.setSocketFactory方法的典型用法代码示例。如果您正苦于以下问题:Java MqttConnectOptions.setSocketFactory方法的具体用法?Java MqttConnectOptions.setSocketFactory怎么用?Java MqttConnectOptions.setSocketFactory使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.eclipse.paho.client.mqttv3.MqttConnectOptions的用法示例。


在下文中一共展示了MqttConnectOptions.setSocketFactory方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: buildMqttConnectOptions

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private MqttConnectOptions buildMqttConnectOptions(AbstractAwsIotClient client, SocketFactory socketFactory) {
    MqttConnectOptions options = new MqttConnectOptions();

    options.setSocketFactory(socketFactory);
    options.setCleanSession(true);
    options.setConnectionTimeout(client.getConnectionTimeout() / 1000);
    options.setKeepAliveInterval(client.getKeepAliveInterval() / 1000);

    Set<String> serverUris = getServerUris();
    if (serverUris != null && !serverUris.isEmpty()) {
        String[] uriArray = new String[serverUris.size()];
        serverUris.toArray(uriArray);
        options.setServerURIs(uriArray);
    }

    if (client.getWillMessage() != null) {
        AWSIotMessage message = client.getWillMessage();

        options.setWill(message.getTopic(), message.getPayload(), message.getQos().getValue(), false);
    }

    return options;
}
 
开发者ID:aws,项目名称:aws-iot-device-sdk-java,代码行数:24,代码来源:AwsIotMqttConnection.java

示例2: connect

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
public void connect() {
  try {
    client = new MqttAsyncClient(
        (configuration.isSsl() ? "ssl" : "tcp") + "://" + configuration.getHost() + ":" + configuration.getPort(),
        getClientId(), new MemoryPersistence());
    client.setCallback(this);
    clientOptions = new MqttConnectOptions();
    clientOptions.setCleanSession(true);
    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, null);
    clientOptions.setSocketFactory(sslContext.getSocketFactory());

    if (configuration.isSsl() && !StringUtils.isEmpty(configuration.getTruststore())) {
      Properties sslProperties = new Properties();
      sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORE, configuration.getTruststore());
      sslProperties.put(SSLSocketFactoryFactory.TRUSTSTOREPWD, configuration.getTruststorePassword());
      sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORETYPE, "JKS");
      sslProperties.put(SSLSocketFactoryFactory.CLIENTAUTH, false);
      clientOptions.setSSLProperties(sslProperties);
    }
    configuration.getCredentials().configure(clientOptions);
    checkConnection();
    if (configuration.getAttributeUpdates() != null) {
      configuration.getAttributeUpdates().forEach(
          mapping -> gateway.subscribe(new AttributesUpdateSubscription(mapping.getDeviceNameFilter(), this)));
    }
    if (configuration.getServerSideRpc() != null) {
      configuration.getServerSideRpc()
          .forEach(mapping -> gateway.subscribe(new RpcCommandSubscription(mapping.getDeviceNameFilter(), this)));
    }
  } catch (MqttException | NoSuchAlgorithmException | KeyManagementException e) {
    log.error("[{}:{}] MQTT broker connection failed!", configuration.getHost(), configuration.getPort(), e);
    throw new RuntimeException("MQTT broker connection failed!", e);
  }
}
 
开发者ID:osswangxining,项目名称:iotgateway,代码行数:36,代码来源:MqttBrokerMonitor.java

示例3: createMqttAsyncClient

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private void createMqttAsyncClient(Properties deviceProps) throws MqttException, 
NoSuchAlgorithmException, 
KeyManagementException {
	
	StringBuilder serverURI = new StringBuilder();
	StringBuilder clientId = new StringBuilder();
	
	serverURI.append("ssl://")
			 .append(trimedValue(deviceProps.getProperty("Organization-ID")))
			 .append(".messaging.internetofthings.ibmcloud.com:8883");
	
	clientId.append("d:")
	         .append(trimedValue(deviceProps.getProperty("Organization-ID")))
	         .append(":")
	         .append(trimedValue(deviceProps.getProperty("Device-Type")))
	         .append(":")
	         .append(trimedValue(deviceProps.getProperty("Device-ID")));
	
	MqttConnectOptions conOpt = new MqttConnectOptions();
	conOpt.setCleanSession(false);
	conOpt.setUserName("use-token-auth");
	conOpt.setPassword(trimedValue(deviceProps.getProperty("Authentication-Token")).toCharArray());
	SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
	sslContext.init(null, null, null);
	conOpt.setSocketFactory(sslContext.getSocketFactory());
	
	
	mqttAsyncClient = new MqttAsyncClient(serverURI.toString(), clientId.toString());
	System.out.println("Trying to connect to URI -> "+serverURI.toString() +" ClientID: "+clientId.toString());
	System.out.println("Username : "+conOpt.getUserName());
	System.out.println("password : "+new String(conOpt.getPassword()));
	mqttAsyncClient.connect(conOpt);
}
 
开发者ID:ibm-watson-iot,项目名称:iot-device-samples,代码行数:34,代码来源:SampleRasPiDMAgentWithCustomMqttAsyncClient.java

示例4: createMqttClient

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private void createMqttClient(Properties deviceProps) throws MqttException, 
NoSuchAlgorithmException, 
KeyManagementException {
	
	StringBuilder serverURI = new StringBuilder();
	StringBuilder clientId = new StringBuilder();
	
	serverURI.append("ssl://")
			 .append(trimedValue(deviceProps.getProperty("Organization-ID")))
			 .append(".messaging.internetofthings.ibmcloud.com:8883");
	
	clientId.append("d:")
	         .append(trimedValue(deviceProps.getProperty("Organization-ID")))
	         .append(":")
	         .append(trimedValue(deviceProps.getProperty("Device-Type")))
	         .append(":")
	         .append(trimedValue(deviceProps.getProperty("Device-ID")));
	
	MqttConnectOptions conOpt = new MqttConnectOptions();
	conOpt.setCleanSession(false);
	conOpt.setUserName("use-token-auth");
	conOpt.setPassword(trimedValue(deviceProps.getProperty("Authentication-Token")).toCharArray());
	SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
	sslContext.init(null, null, null);
	conOpt.setSocketFactory(sslContext.getSocketFactory());
	
	
	mqttClient = new MqttClient(serverURI.toString(), clientId.toString());
	System.out.println("Trying to connect to URI -> "+serverURI.toString() +" ClientID: "+clientId.toString());
	System.out.println("Username : "+conOpt.getUserName());
	System.out.println("password : "+new String(conOpt.getPassword()));
	mqttClient.connect(conOpt);
}
 
开发者ID:ibm-watson-iot,项目名称:iot-device-samples,代码行数:34,代码来源:SampleRasPiDMAgentWithCustomMqttClient.java

示例5: connect

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
public void connect() {
        try {
            client = new MqttAsyncClient((configuration.isSsl() ? "ssl" : "tcp") + "://" + configuration.getHost() + ":" + configuration.getPort(),
                    getClientId(), new MemoryPersistence());
            client.setCallback(this);
            clientOptions = new MqttConnectOptions();
//            clientOptions.setUserName("a-u88ncg-1qo8utyxwr");
//            clientOptions.setPassword("KB?fB1sG-1GFb?wLvx".toCharArray());
            clientOptions.setCleanSession(true);
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, null, null);
            clientOptions.setSocketFactory(sslContext.getSocketFactory());
            
            if (configuration.isSsl() && !StringUtils.isEmpty(configuration.getTruststore())) {
                Properties sslProperties = new Properties();
                sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORE, configuration.getTruststore());
                sslProperties.put(SSLSocketFactoryFactory.TRUSTSTOREPWD, configuration.getTruststorePassword());
                sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORETYPE, "JKS");
                sslProperties.put(SSLSocketFactoryFactory.CLIENTAUTH, false);
                clientOptions.setSSLProperties(sslProperties);
            }
            configuration.getCredentials().configure(clientOptions);
          
//          Properties props = new Properties();
//          props.put("id", "appId001");
//          props.put("Organization-ID", "u88ncg");
//          props.put("Authentication-Method", "apikey");
//          props.put("API-Key", "a-u88ncg-1qo8utyxwr");
//          props.put("Authentication-Token", "KB?fB1sG-1GFb?wLvx");
//          props.put("Device-Type", "DC_SensorType");
//          props.put("Device-ID", "my-device-001");
//          props.put("Shared-Subscription", "false");
//          props.put("Clean-Session", "true");
//          
//          myClient = new ApplicationClient(props);
          
            client.connect(clientOptions).waitForCompletion(1000 * 60);
            if (client.isConnected()) {
              System.out.println("Successfully connected " + "to the IBM Watson IoT Platform");
            }
            
            checkConnection();
            if (configuration.getAttributeUpdates() != null) {
                configuration.getAttributeUpdates().forEach(mapping ->
                        gateway.subscribe(new AttributesUpdateSubscription(mapping.getDeviceNameFilter(), this))
                );
            }
            if (configuration.getServerSideRpc() != null) {
                configuration.getServerSideRpc().forEach(mapping ->
                        gateway.subscribe(new RpcCommandSubscription(mapping.getDeviceNameFilter(), this))
                );
            }
        } catch (Exception e) {
            log.error("[{}:{}] MQTT broker connection failed!", configuration.getHost(), configuration.getPort(), e);
            throw new RuntimeException("MQTT broker connection failed!", e);
        }
    }
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:58,代码来源:WiotpMqttBrokerMonitor.java

示例6: configure

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
@Override
public void configure(MqttConnectOptions clientOptions) {
  clientOptions.setSocketFactory(getSocketFactory());
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:5,代码来源:CertPemClientCredentials.java

示例7: configure

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
@Override
public void configure(MqttConnectOptions clientOptions) {
    clientOptions.setSocketFactory(getSocketFactory());
}
 
开发者ID:thingsboard,项目名称:thingsboard-gateway,代码行数:5,代码来源:CertPemClientCredentials.java

示例8: establishMqttSession

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
/**
 * Establish an MQTT Session with Sparkplug defined Death Certificate. It may not be
 * Immediately intuitive that the Death Certificate is created prior to publishing the
 * Birth Certificate, but the Death Certificate is actually part of the MQTT Session 
 * establishment. For complete details of the actual MQTT wire protocol refer to the 
 * latest OASyS MQTT V3.1.1 standards at:
 * http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html
 * 
 * @return true = MQTT Session Established
 */
public boolean establishMqttSession() {
	try {

		//
		// Setup the MQTT connection parameters using the Paho MQTT Client.
		//
		MqttConnectOptions options = new MqttConnectOptions();
		
		if (USING_REAL_TLS) {
			SocketFactory sf = SSLSocketFactory.getDefault();
			options.setSocketFactory(sf);
		}
		
		// Autoreconnect enable
		options.setAutomaticReconnect(true);
		// MQTT session parameters Clean Start = true
		options.setCleanSession(true);
		// Session connection attempt timeout period in seconds
		options.setConnectionTimeout(10);
		// MQTT session parameter Keep Alive Period in Seconds
		options.setKeepAliveInterval(30);
		// MQTT Client Username
		options.setUserName(username);
		// MQTT Client Password
		options.setPassword(password.toCharArray());
		//
		// Build up the Death Certificate MQTT Payload. Note that the Death
		// Certificate payload sequence number
		// is not tied to the normal message sequence numbers.
		//
		SparkplugBPayload payload = new SparkplugBPayloadBuilder(getNextSeqNum())
				.setTimestamp(new Date())
				.addMetric(new MetricBuilder("bdSeq",
						MetricDataType.Int64,
						bdSeq)
						.createMetric())
				.createPayload();
		byte[] bytes = new SparkplugBPayloadEncoder().getBytes(payload);
		//
		// Setup the Death Certificate Topic/Payload into the MQTT session
		// parameters
		//
		options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, bytes, 0, false);

		//
		// Create a new Paho MQTT Client
		//
		client = new MqttClient(serverUrl, clientId);
		//
		// Using the parameters set above, try to connect to the define MQTT
		// server now.
		//
		System.out.println("Trying to establish an MQTT Session to the MQTT Server @ :" + serverUrl);
		client.connect(options);
		System.out.println("MQTT Session Established");
		client.setCallback(this);
		//
		// With a successful MQTT Session in place, now issue subscriptions
		// for the EoN Node and Device "Command" Topics of 'NCMD' and 'DCMD'
		// defined in Sparkplug
		//
		client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
		client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);
	} catch (Exception e) {
		System.out.println("Error Establishing an MQTT Session:");
		e.printStackTrace();
		return false;
	}
	return true;
}
 
开发者ID:Cirrus-Link,项目名称:Sparkplug,代码行数:81,代码来源:SparkplugRaspberryPiExample.java

示例9: run

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
public void run() {
	try {
		// Random generator and thread pool for outgoing published messages
		executor = Executors.newFixedThreadPool(1);
		
		// Build up DEATH payload - note DEATH payloads don't have a regular sequence number
		SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date());
		deathPayload = addBdSeqNum(deathPayload);
		byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload());
		
		MqttConnectOptions options = new MqttConnectOptions();
		
		if (USING_REAL_TLS) {
			SocketFactory sf = SSLSocketFactory.getDefault();
			options.setSocketFactory(sf);
		}
		
		// Connect to the MQTT Server
		options.setAutomaticReconnect(true);
		options.setCleanSession(true);
		options.setConnectionTimeout(30);
		options.setKeepAliveInterval(30);
		options.setUserName(username);
		options.setPassword(password.toCharArray());
		options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false);
		client = new MqttClient(serverUrl, clientId);
		client.setTimeToWait(2000);	
		client.setCallback(this);					// short timeout on failure to connect
		client.connect(options);
		
		// Subscribe to control/command messages for both the edge of network node and the attached devices
		client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
		client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);	
		client.subscribe(NAMESPACE + "/#", 0);	
		
		// Loop forever publishing data every PUBLISH_PERIOD
		while (true) {
			Thread.sleep(PUBLISH_PERIOD);

			if (client.isConnected()) {
				synchronized(seqLock) {
					System.out.println("Connected - publishing new data");
					// Create the payload and add some metrics
					SparkplugBPayload payload = new SparkplugBPayload(
							new Date(), 
							newMetrics(false), 
							getSeqNum(),
							newUUID(), 
							null);
					
					client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId, 
							new SparkplugBPayloadEncoder().getBytes(payload), 0, false);
				}
			} else {
				System.out.println("Not connected - not publishing data");
			}
		}
	} catch(Exception e) {
		e.printStackTrace();
	}
}
 
开发者ID:Cirrus-Link,项目名称:Sparkplug,代码行数:62,代码来源:SparkplugExample.java

示例10: run

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
public void run() {
	try {
		// Random generator and thread pool for outgoing published messages
		executor = Executors.newFixedThreadPool(1);

		// Build up DEATH payload - note DEATH payloads don't have a regular sequence number
		SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date());
		deathPayload = addBdSeqNum(deathPayload);
		byte[] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload());

		MqttConnectOptions options = new MqttConnectOptions();

		if (USING_REAL_TLS) {
			SocketFactory sf = SSLSocketFactory.getDefault();
			options.setSocketFactory(sf);
		}

		// Connect to the MQTT Server
		options.setAutomaticReconnect(true);
		options.setCleanSession(true);
		options.setConnectionTimeout(30);
		options.setKeepAliveInterval(30);
		options.setUserName(username);
		options.setPassword(password.toCharArray());
		options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false);
		client = new MqttClient(serverUrl, clientId);
		client.setTimeToWait(2000);
		client.setCallback(this); // short timeout on failure to connect
		client.connect(options);

		// Subscribe to control/command messages for both the edge of network node and the attached devices
		client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
		client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);

		// Loop forever publishing data every PUBLISH_PERIOD
		while (true) {
			Thread.sleep(PUBLISH_PERIOD);

			if (client.isConnected()) {
				synchronized (seqLock) {
					System.out.println("Connected - publishing new data");
					// Create the payload and add some metrics
					SparkplugBPayload payload = new SparkplugBPayload(new Date(), newComplexTemplateInstance(),
							getSeqNum(), newUUID(), null);

					client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId,
							new SparkplugBPayloadEncoder().getBytes(payload), 0, false);
				}
			} else {
				System.out.println("Not connected - not publishing data");
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
开发者ID:Cirrus-Link,项目名称:Sparkplug,代码行数:57,代码来源:SparkplugExample.java

示例11: main

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
public static void main(String[] args) {

        try {
            URL ksUrl = Resources.getResource(KEY_STORE_FILE);
            File ksFile = new File(ksUrl.toURI());
            URL tsUrl = Resources.getResource(KEY_STORE_FILE);
            File tsFile = new File(tsUrl.toURI());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore trustStore = KeyStore.getInstance(JKS);
            char[] ksPwd = new char[]{0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x5F, 0x6B, 0x73, 0x5F, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64};
            trustStore.load(new FileInputStream(tsFile), ksPwd);
            tmf.init(trustStore);
            KeyStore ks = KeyStore.getInstance(JKS);

            ks.load(new FileInputStream(ksFile), ksPwd);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            char[] clientPwd = new char[]{0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x5F, 0x6B, 0x65, 0x79, 0x5F, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64};
            kmf.init(ks, clientPwd);

            KeyManager[] km = kmf.getKeyManagers();
            TrustManager[] tm = tmf.getTrustManagers();
            SSLContext sslContext = SSLContext.getInstance(TLS);
            sslContext.init(km, tm, null);

            MqttConnectOptions options = new MqttConnectOptions();
            options.setSocketFactory(sslContext.getSocketFactory());
            MqttAsyncClient client = new MqttAsyncClient(MQTT_URL, CLIENT_ID);
            client.connect(options);
            Thread.sleep(3000);
            MqttMessage message = new MqttMessage();
            message.setPayload("{\"key1\":\"value1\", \"key2\":true, \"key3\": 3.0, \"key4\": 4}".getBytes());
            client.publish("v1/devices/me/telemetry", message);
            client.disconnect();
            log.info("Disconnected");
            System.exit(0);
        } catch (Exception e) {
            log.error("Unexpected exception occurred in MqttSslClient", e);
        }
    }
 
开发者ID:thingsboard,项目名称:thingsboard,代码行数:42,代码来源:MqttSslClient.java


注:本文中的org.eclipse.paho.client.mqttv3.MqttConnectOptions.setSocketFactory方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。