本文整理匯總了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;
}
示例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);
}
}
示例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);
}
}
示例6: configure
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
@Override
public void configure(MqttConnectOptions clientOptions) {
clientOptions.setSocketFactory(getSocketFactory());
}
示例7: configure
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
@Override
public void configure(MqttConnectOptions clientOptions) {
clientOptions.setSocketFactory(getSocketFactory());
}
示例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;
}
示例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();
}
}
示例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();
}
}
示例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);
}
}