Third, the server code implementation

After the new project, you should first import the download time before we build mosquitto server jar package, download address is:

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

1. Import jar package

Proceed as follows:

 

 

 

After completion of the above steps is such that:

 

 

 

 

 

2. The server code:

 A. receiving a message:

 First, we must first define the variables we need:

    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;

Next we write the code embodied in the start () method:

. A instantiate client:

Select three parameters required MqttClient constructor, the parameters are HOST, client, new MemoryPersistence ()

. B instantiation options:

Direct use here the default constructor like

. C turn call options of five methods:

setCleanSession(true)

Role is to set whether empty session, where if set to false indicates that the server retains the client's connection record, set here to represent true every time you connect to the server are connected to a new identity

setUserName(userName)

Role is to set the user name connected

setPassword(passWord.toCharArray())

Role is to set a password connection

setConnectionTimeout (// Time)

Role is to set the timeout in seconds

options.setKeepAliveInterval (// Time)

Function is provided heartbeat session server seconds every 1.5 seconds * 20 transmits messages to the client determines whether the client is online but this method does not reconnection mechanism

d. Set callback

client.setCallback(new PushCallback())

e. Subscribe topic

MqttTopic topic = client.getTopic(TOPIC)

f. connection

client.connect(options);

g. Subscribe to news

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

 

B. message callback

Message callback class used in three methods:

public void connectionLost (Throwable cause): After the connection is lost, there is generally performed in reconnection  

public void deliveryComplete (IMqttDeliveryToken token): sent successfully

public void messageArrived (String topic, MqttMessage message): After the subscribe message is executed to get inside 

 

Guess you like

Origin www.cnblogs.com/Somture478/p/11856053.html