sachinrj
sachinrj

Reputation: 3

MQTT- JAVA client program

I have written the PAHO-client MQTT programs in Java and using mosquitto-broker.

Publisher snippet code: Publisher sending the numbers from 0 to 254.

char[] charset = new  char[255]; 
for(int i=0;i< 255;i++)
{
    charset[i] = (char)i;
    System.out.println(i+" "+(int)charset[i]);
}

String str2 = String.valueOf(charset);
MqttMessage message1 = new MqttMessage();
message1.setPayload(str2.getBytes());            
client.publish("temperature",message1);

Subscriber snippet code: Subscriber is expected to recieve numbers from 0 to 254.

byte[] ascii = message.getBytes(); 
for (int i = 0; i <ascii.length; i++) 
{                         
       System.out.println(i +" "+(long)(ascii[i] & 0xFF));                                           
}

Output Snapshots: Publisher output

subscriber ouput

Problem in subscriber output:

The index from 128 to 159 in subscriber output is receiving the value '63' instead of the normal numbers which are being sent from publisher side.

Upvotes: 0

Views: 938

Answers (1)

wiomoc
wiomoc

Reputation: 1089

Why not using byte arrays

Publisher

byte[] payload = new byte[255]; 
for(int i = 0; i < 255;i ++) {
    payload[i] = (byte)i;
}

message.setPayload(payload);            
client.publish("temperature", message);

Subscriber

byte[] paylaod = message.getPayload();
for (int i = 0; i < payload.length; i++) {                         
       System.out.println(i +" "+(int)(payload[i] & 0xFF));                                           
}

But the problem is mostly related how Java encodes String a char is a 16-bit UTF-16 encoded character. A String is a "char array with additional features".

So if you call String#getBytes() the UTF-16 data gets converted to UTF-8, which causes in your case data loose. String are not designed to carry binary Data

Upvotes: 2

Related Questions