Skip to content

Commit 4d37d19

Browse files
committed
mqtt 上传数据
1 parent 43867fa commit 4d37d19

1 file changed

Lines changed: 11 additions & 24 deletions

File tree

src/main/java/lambdasinaction/mqtt/demo2/MqttPublishSample.java

Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import org.eclipse.paho.client.mqttv3.MqttMessage;
77
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
88

9+
import java.util.Arrays;
10+
911
/**
1012
* Created by DW on 2017/5/2.
1113
*/
@@ -14,8 +16,8 @@ public class MqttPublishSample {
1416
public static void main(String[] args) {
1517

1618
String topic = "$dp";
17-
String content = "{\"datastreams\":[{\"id\":\"led\", \"datapoints\":[{\"value\": 30.2}]}]}";
18-
int qos = 2;
19+
String content = "{\"datastreams\":[{\"id\":\"abc\", \"datapoints\":[{\"value\": 30.2}]}]}";
20+
int qos = 1;
1921
String broker = "tcp://183.230.40.39:6002";
2022
String clientId = "5280490";
2123
String userName = "84661";
@@ -33,33 +35,18 @@ public static void main(String[] args) {
3335
sampleClient.connect(connOpts);
3436
System.out.println("Connected");
3537
System.out.println("Publishing message: "+content);
36-
MqttMessage message = new MqttMessage(content.getBytes());
38+
MqttMessage message = new MqttMessage();
3739
message.setQos(qos);
3840

39-
/* String str ="{\"datastreams\":[{\"id\":\"led\", \"datapoints\":[{\"value\": 30.2}]}]}";
40-
41-
byte[] buf = new byte[10];
42-
43-
buf[0]=0x01; // Byte 1 json格式1字符串
44-
45-
buf[1]=0x00; //Byte 2 数据流 json的长度的高位字节
46-
Integer iO = new Integer(str.length());
47-
buf[2]=iO.byteValue(); // Byte3 数据流 json的长度的高位字节
48-
message.setPayload(buf);*/
49-
50-
// 实例化一个UnicodeEncoding对象,用于转换.
51-
// UnicodeEncoding unicode = new UnicodeEncoding();
5241
byte[] bytes = new byte[2000];
53-
bytes[0] = Byte.parseByte("1");
54-
bytes[1] = 0x00;
55-
bytes[2] = 0x41;
56-
/* bytes[1] = Byte.parseByte("0");
57-
bytes[2] = Byte.parseByte(content.length() + "");
58-
bytes[3] = Byte.parseByte(content);*/
59-
60-
//message.setPayload(bytes);
42+
bytes[0] = 0x01;
43+
bytes[1] = (byte) (content.length() >>> 8);
44+
bytes[2] = (byte) (content.length() & 0xff);
45+
byte[] json = content.getBytes();
6146

47+
System.arraycopy(json, 0, bytes, 3, json.length);
6248

49+
message.setPayload(bytes);
6350

6451
sampleClient.publish(topic, message);
6552
System.out.println("Message published");

0 commit comments

Comments
 (0)