MqttServerTest.java 2.3 KB
Newer Older
如梦技术's avatar
如梦技术 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & www.net.dreamlu.net).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

如梦技术's avatar
如梦技术 已提交
17
package net.dreamlu.iot.mqtt.server;
如梦技术's avatar
如梦技术 已提交
18

19 20 21
import net.dreamlu.iot.mqtt.codec.ByteBufferUtil;
import net.dreamlu.iot.mqtt.codec.MqttQoS;
import net.dreamlu.iot.mqtt.core.common.MqttSubscription;
如梦技术's avatar
如梦技术 已提交
22
import net.dreamlu.iot.mqtt.core.server.DefaultMqttServerSubManager;
23
import net.dreamlu.iot.mqtt.core.server.IMqttMessageIdGenerator;
如梦技术's avatar
如梦技术 已提交
24
import net.dreamlu.iot.mqtt.core.server.MqttServer;
如梦技术's avatar
如梦技术 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Timer;
import java.util.TimerTask;

/**
 * mqtt 服务端测试
 *
 * @author L.cm
 */
public class MqttServerTest {

	public static void main(String[] args) throws IOException {
如梦技术's avatar
如梦技术 已提交
39
		DefaultMqttServerSubManager subManager = new DefaultMqttServerSubManager();
如梦技术's avatar
如梦技术 已提交
40 41
		// 服务端注册订阅
		subManager.subscribe(new MqttSubscription(MqttQoS.AT_MOST_ONCE, "/test/#", ((topic, payload) -> {
42 43 44 45
			System.out.println(topic + '\t' + ByteBufferUtil.toString(payload));
		})));

		IMqttMessageIdGenerator messageIdGenerator = new MqttMessageIdGenerator();
如梦技术's avatar
如梦技术 已提交
46 47
		MqttSubscribeStore subscribeStore = new MqttSubscribeStore();
		MqttPublishManager publishManager = new MqttPublishManager();
如梦技术's avatar
如梦技术 已提交
48 49 50 51 52
		MqttServer mqttServer = MqttServer.create()
			// 默认:127.0.0.1
			.ip("127.0.0.1")
			// 默认:1883
			.port(1883)
53
			.messageIdGenerator(messageIdGenerator)
如梦技术's avatar
如梦技术 已提交
54 55 56
			.publishManager(publishManager)
			.subManager(subManager)
			.subscribeStore(subscribeStore)
如梦技术's avatar
如梦技术 已提交
57
			.debug() // 开启 debug 信息日志
如梦技术's avatar
如梦技术 已提交
58 59
			.start();

如梦技术's avatar
如梦技术 已提交
60 61 62 63
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
64
				mqttServer.publishAll("/test/123", ByteBuffer.wrap("mica最牛皮".getBytes()));
如梦技术's avatar
如梦技术 已提交
65 66 67 68
			}
		}, 1000, 2000);
	}
}