我正在尝试与MQTT服务器建立并发会话,一旦所有连接建立,所有客户端将断开连接。
在下面的发布者代码中,我尝试进行并发会话,每个会话发送50条消息。像这样,将创建500个线程,每个线程将发送50条消息。但是创建100个连接需要10分钟。编码中是否有任何错误,并且可能降低下面代码中的连接速度变化率,因为我在Golang中编写的同一件事那里的连接率很高。
下面是发布者代码:
ImportError: No module named numpy
下面是主要方法:
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
public class Publisher extends Thread{
public static final String test_topic = "test";
private MqttClient client;
public static final String BROKER_URL = "tcp://192.168.1.129:1883";
CountDownLatch latch;
public Publisher(CountDownLatch latch) {
super();
this.latch = latch;
}
public void Publisher() {
String clientid=Thread.currentThread().getName();
System.out.println("=========== "+clientid);
MqttConnectOptions options = null;
try {
client = new MqttClient(BROKER_URL, clientid);
options = new MqttConnectOptions();
options.setCleanSession(true);
options.setMaxInflight(50);
client.connect(options);
} catch (MqttException e) {
try {
client.connect(options);
} catch (MqttSecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MqttException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
//System.exit(1);
}
}
@Override
public void run() {
// TODO Auto-generated method stub
Publisher();
System.out.println(Thread.currentThread().getName());
try {
for(int i=0;i<50;i++)
{
//Thread.sleep(20);
publishTemperature();
}
} catch (MqttPersistenceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /*catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
public void publishTemperature() throws MqttPersistenceException, MqttException {
final MqttTopic test = client.getTopic(test_topic);
final String temperature=""{\"test\":\"test\"}"";
test.publish(new MqttMessage(temperature.getBytes()));
//System.out.println("Published data. Topic: " + "test" + " Message: " + temperature);
}
public MqttClient getClient() {
return client;
}
public void setClient(MqttClient client) {
this.client = client;
}
}
这里所有连接都将连接,并建立持久连接,直至达到500个连接。此后,所有连接将断开一次。
答案 0 :(得分:0)
删除以下行:
Publisher[i].join();
Thread.join()的文档如下:
公共最终无效join() 抛出InterruptedException
等待该线程死亡。
此方法的调用行为与 调用
join(0)
这意味着每次循环时,它将停止并等待该线程完成其任务,然后再创建新线程。
如果删除该调用,它将允许所有线程并行运行。