Java MQTT从主题接收消息
我正在编写一个从MQTT代理接收消息的程序 服务器从客户端获取ID并使其成为主题的名称:例如,topic1、topic2。 然后在订阅时,服务器传递主题的名称,然后从该主题读取消息。 这是我的服务器:Java MQTT从主题接收消息,java,tcp,cloud,mqtt,broker,Java,Tcp,Cloud,Mqtt,Broker,我正在编写一个从MQTT代理接收消息的程序 服务器从客户端获取ID并使其成为主题的名称:例如,topic1、topic2。 然后在订阅时,服务器传递主题的名称,然后从该主题读取消息。 这是我的服务器: public class AnalyticServer { // The server socket. private static ServerSocket serverSocket = null; // The client socket. p
public class AnalyticServer {
// The server socket.
private static ServerSocket serverSocket = null;
// The client socket.
private static Socket clientSocket = null;
// This server can accept up to maxClientsCount clients' connections.
private static final int maxClientsCount = 5;
private static final clientThread[] threads = new clientThread[maxClientsCount];
public static void main(String args[]) throws MqttException, InterruptedException {
// The default port number.
int portNumber = 4544;
//Open Server
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println(e);
}
//
//When server is listening
System.out.println("Server is now listening at port 4544");
while (true) {
try {
//Make connection
clientSocket = serverSocket.accept();
System.out.println("Connected");
int i = 0;
//Find thread null to run the connection
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket, threads)).start();
break;
}
}
if (i == maxClientsCount) {
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server is now, please try again later");
os.close();
clientSocket.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
}
}
//Thread control each Request
class clientThread extends Thread {
private Socket clientSocket = null;
private final clientThread[] threads;
private int maxClientsCount;
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
}
public void run() {
int maxClientsCount = this.maxClientsCount;
clientThread[] threads = this.threads;
try {
int identifier=0;
//get id
InputStream input = null;
input = clientSocket.getInputStream();
identifier=input.read();
String topic="topic".concat(String.valueOf(identifier));
//Subscribe
try {
System.out.println("subscribing");
Subscribe receive=new Subscribe(topic);
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// open image
FileInputStream imgPath = new FileInputStream("image.jpg");
BufferedImage bufferedImage = ImageIO.read(imgPath);
Thread.sleep(1200);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bufferedImage, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
//SendImage
DataOutputStream outToClient = new DataOutputStream(clientSocket.getOutputStream());
outToClient.write(imageInByte);
System.out.println(outToClient.size());
clientSocket.close();
} catch (IOException e) {
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
subscribe构造函数中的主题是正确的,但是this.client.setCallbackthis似乎没有调用messageArrived方法。所以我什么也收不到
有人知道吗?
非常感谢关于您的订阅者,您的帖子还不够多,但这里有一个简单的实用方法:
import java.io.IOException;
import java.sql.Timestamp;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
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.persist.MqttDefaultFilePersistence;
public class TestSub implements MqttCallback
{
public static void main(String[] args)
{
String url = "tcp://iot.eclipse.org:1883";
String clientId = "TestSub_"+System.currentTimeMillis();
String topicName = "test/ABC/one";
int qos = 1;
boolean cleanSession = true;
String userName = "myUserId";
String password = "mypwd";
try
{
new TestSub(url, clientId, cleanSession, userName, password, topicName, qos);
}
catch (MqttException me)
{
System.out.println(me.getLocalizedMessage());
System.out.println(me.getCause());
me.printStackTrace();
}
}
public TestSub(String url, String clientId, boolean cleanSession, String userName, String password, String topicName, int qos) throws MqttException
{
String tmpDir = System.getProperty("java.io.tmpdir");
MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
MqttClient client;
MqttConnectOptions conOpt;
try
{
conOpt = new MqttConnectOptions();
conOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_DEFAULT);
conOpt.setCleanSession(cleanSession);
if (userName != null)
conOpt.setUserName(userName);
if (password != null)
conOpt.setPassword(password.toCharArray());
// Construct an MQTT blocking mode client
client = new MqttClient(url, clientId, dataStore);
// Set this wrapper as the callback handler
client.setCallback(this);
// Connect to the MQTT server
client.connect(conOpt);
System.out.println("Connected to " + url + " with client ID " + client.getClientId());
System.out.println("Subscribing to topic \"" + topicName + "\" qos " + qos);
client.subscribe(topicName, qos);
// Continue waiting for messages until the Enter is pressed
System.out.println("Press <Enter> to exit");
try
{
System.in.read();
}
catch (IOException e)
{
// If we can't read we'll just exit
}
// Disconnect the client from the server
client.disconnect();
System.out.println("Disconnected");
}
catch (MqttException e)
{
e.printStackTrace();
System.out.println("Unable to set up client: " + e.toString());
System.exit(1);
}
}
public void connectionLost(Throwable cause)
{
System.out.println("Connection lost! " + cause.getLocalizedMessage());
System.exit(1);
}
public void deliveryComplete(IMqttDeliveryToken token)
{
}
public void messageArrived(String topic, MqttMessage message)
throws MqttException
{
String time = new Timestamp(System.currentTimeMillis()).toString();
System.out.println("Time:\t" + time + " Topic:\t" + topic + " Message:\t" + new String(message.getPayload()));
}
}
您已将用户名和密码包含在源代码中,最好的办法是删除该问题并使用该信息再次询问。hiddenoh我忘记了,非常感谢。@ngoc anh该信息仍在编辑历史记录中。完全删除问题并再次提问。还要更改该用户的密码
import java.io.IOException;
import java.sql.Timestamp;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
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.persist.MqttDefaultFilePersistence;
public class TestSub implements MqttCallback
{
public static void main(String[] args)
{
String url = "tcp://iot.eclipse.org:1883";
String clientId = "TestSub_"+System.currentTimeMillis();
String topicName = "test/ABC/one";
int qos = 1;
boolean cleanSession = true;
String userName = "myUserId";
String password = "mypwd";
try
{
new TestSub(url, clientId, cleanSession, userName, password, topicName, qos);
}
catch (MqttException me)
{
System.out.println(me.getLocalizedMessage());
System.out.println(me.getCause());
me.printStackTrace();
}
}
public TestSub(String url, String clientId, boolean cleanSession, String userName, String password, String topicName, int qos) throws MqttException
{
String tmpDir = System.getProperty("java.io.tmpdir");
MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
MqttClient client;
MqttConnectOptions conOpt;
try
{
conOpt = new MqttConnectOptions();
conOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_DEFAULT);
conOpt.setCleanSession(cleanSession);
if (userName != null)
conOpt.setUserName(userName);
if (password != null)
conOpt.setPassword(password.toCharArray());
// Construct an MQTT blocking mode client
client = new MqttClient(url, clientId, dataStore);
// Set this wrapper as the callback handler
client.setCallback(this);
// Connect to the MQTT server
client.connect(conOpt);
System.out.println("Connected to " + url + " with client ID " + client.getClientId());
System.out.println("Subscribing to topic \"" + topicName + "\" qos " + qos);
client.subscribe(topicName, qos);
// Continue waiting for messages until the Enter is pressed
System.out.println("Press <Enter> to exit");
try
{
System.in.read();
}
catch (IOException e)
{
// If we can't read we'll just exit
}
// Disconnect the client from the server
client.disconnect();
System.out.println("Disconnected");
}
catch (MqttException e)
{
e.printStackTrace();
System.out.println("Unable to set up client: " + e.toString());
System.exit(1);
}
}
public void connectionLost(Throwable cause)
{
System.out.println("Connection lost! " + cause.getLocalizedMessage());
System.exit(1);
}
public void deliveryComplete(IMqttDeliveryToken token)
{
}
public void messageArrived(String topic, MqttMessage message)
throws MqttException
{
String time = new Timestamp(System.currentTimeMillis()).toString();
System.out.println("Time:\t" + time + " Topic:\t" + topic + " Message:\t" + new String(message.getPayload()));
}
}