使用MQTT协议的订阅发布模式,实现从服务器推送消息到客户端功能。

1、服务端需要先使用Apollo作为代理服务器来发消息,参考此文即可搭建:
https://blog.csdn.net/marrn/article/details/71141122?utm_source=itdadao&utm_medium=referral
2、PC端通过java代码,通过MQTT协议来连接服务器,然后在根据界面动作 ,发布消息;

3、手机端设置相同的连接主题参数,订阅消息。

关键代码:

PC端

//服务器端口 账号 密码 private String host = "tcp://127.0.0.1:61613"; private String userName = "admin"; private String passWord = "123";

//客户端对象、主题、发布消息、共同主题 private MqttClient client; private MqttTopic topic; private MqttMessage message; private String myTopic = "test/topic";

        //创建客户端 client = new MqttClient(host, "Server", new MemoryPersistence());

private void connect() {
//设置连接参数
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setUserName(userName);
options.setPassword(passWord.toCharArray());
// 设置超时时间
options.setConnectionTimeout(10);
// 设置会话心跳时间
options.setKeepAliveInterval(20);
try {
//设置客户端回掉
client.setCallback(new MqttCallback() {


@Override
public void connectionLost(Throwable cause) {
System.out.println("connectionLost-----------");
}


@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("deliveryComplete---------"
+ token.isComplete());
}


@Override
public void messageArrived(String topic, MqttMessage arg1)
throws Exception {
System.out.println("messageArrived----------");


}
});


topic = client.getTopic(myTopic);
System.out.println("------topic=" + topic.toString());

message = new MqttMessage();
message.setQos(1);
message.setRetained(true);
System.out.println("------ratained状态" + message.isRetained());
message.setPayload("msg-hnac".getBytes());
//连接
client.connect(options);
} catch (Exception e) {
e.printStackTrace();
}

}



手机端也类似,配置相同的IP和端口,设置连接参数之后,需要进行订阅:

            // 订阅主题

            client.subscribe(PushConfig.myTopic, 1);


然后PC端delivery后,手机端arrived, 实现推送接收功能。


你可能感兴趣的:(Techonology)