三、服务端代码实现

新建项目后,首先应该导入我们之前搭建mosquitto服务器时下载的jar包,下载地址为:

https://repo.eclipse.org/content/repositories/paho-releases/org/eclipse/paho/

1.导入jar包

步骤如下:

完成上面步骤后是这样的:

扫描二维码关注公众号,回复: 7960120 查看本文章

 

2.服务端代码:

 A.接收消息:

 首先我们要先定义我们所需要的变量:

    public static final String HOST = "tcp://localhost:1883";
    public static final String TOPIC = "onoff";
    private static final String clientid = "client11";
    private MqttClient client;
    private MqttConnectOptions options;
    private String userName = "admin";
    private String passWord = "password";
    private ScheduledExecutorService scheduler;

接下来我们在start()方法中写上具体实现的代码:

a.实例化client:

选择需要的三个参数的MqttClient的构造函数,参数分别为HOST, client, new MemoryPersistence()

b.实例化options:

这里直接使用默认的构造方法就好

c.依次调用options的五个方法:

setCleanSession(true)

作用是设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接

setUserName(userName)

作用是设置连接的用户名

setPassword(passWord.toCharArray())

作用是设置连接的密码

setConnectionTimeout(//时间)

作用是设置超时时间 单位为秒

options.setKeepAliveInterval(//时间)

作用是设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制

d.设置回调

client.setCallback(new PushCallback())

e.订阅主题

MqttTopic topic = client.getTopic(TOPIC)

f.连接

client.connect(options);

g.订阅消息

int[] Qos = {1}
String[] topic1 = {TOPIC}
client.subscribe(topic1, Qos)

B.消息回调

消息回调类中用到三个方法:

public void connectionLost(Throwable cause):连接丢失后,一般在这里面进行重连  

public void deliveryComplete(IMqttDeliveryToken token):是否发送成功

public void messageArrived(String topic, MqttMessage message):subscribe后得到的消息会执行到里面 

猜你喜欢

转载自www.cnblogs.com/Somture478/p/11856053.html