MqttServerTest.java 2.1 KB
Newer Older
如梦技术's avatar
如梦技术 已提交
1
/*
2
 * Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & dreamlu.net).
如梦技术's avatar
如梦技术 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
import net.dreamlu.iot.mqtt.codec.ByteBufferUtil;
如梦技术's avatar
如梦技术 已提交
20
import net.dreamlu.iot.mqtt.core.server.MqttServer;
如梦技术's avatar
如梦技术 已提交
21 22
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
如梦技术's avatar
如梦技术 已提交
23 24 25 26 27 28 29 30 31 32 33

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

/**
 * mqtt 服务端测试
 *
 * @author L.cm
 */
public class MqttServerTest {
如梦技术's avatar
如梦技术 已提交
34
	private static final Logger logger = LoggerFactory.getLogger(MqttServerTest.class);
如梦技术's avatar
如梦技术 已提交
35

36
	public static void main(String[] args) {
如梦技术's avatar
如梦技术 已提交
37
		// 注意:为了能接受更多链接(降低内存),请添加 jvm 参数 -Xss129k
如梦技术's avatar
如梦技术 已提交
38 39 40 41
		MqttServer mqttServer = MqttServer.create()
			// 默认:127.0.0.1
			.ip("127.0.0.1")
			// 默认:1883
42
			.port(1883)
43
			// 默认为: 8092(mqtt 默认最大消息大小),为了降低内存可以减小小此参数,如果消息过大 t-io 会尝试解析多次(建议根据实际业务情况而定)
如梦技术's avatar
如梦技术 已提交
44
			.readBufferSize(512)
45 46 47 48
//			最大包体长度
//			.maxBytesInMessage(1024 * 100)
//			mqtt 3.1 协议会校验 clientId 长度。
//			.maxClientIdLength(64)
49 50 51
			.messageListener((clientId, topic, mqttQoS, payload) -> {
				logger.info("clientId:{} topic:{} mqttQoS:{} message:{}", clientId, topic, mqttQoS, ByteBufferUtil.toString(payload));
			})
如梦技术's avatar
如梦技术 已提交
52
			.debug() // 开启 debug 信息日志
如梦技术's avatar
如梦技术 已提交
53 54
			.start();

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