io.netty.handler.codec.mqtt.MqttPublishMessage Java Examples
The following examples show how to use
io.netty.handler.codec.mqtt.MqttPublishMessage.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsonMqttAdaptor.java From IOT-Technical-Guide with Apache License 2.0 | 6 votes |
private static void convertToGetAttributesRequest(MqttPublishMessage inbound) throws AdaptorException { try { String payload = inbound.payload().toString(UTF8); JsonElement requestBody = new JsonParser().parse(payload); Set<String> clientKeys = toStringSet(requestBody, "clientKeys"); Set<String> sharedKeys = toStringSet(requestBody, "sharedKeys"); if (clientKeys == null && sharedKeys == null) { } else { for (String clientKey : clientKeys) { System.out.print("客户端属性:" + clientKey +" "); } for (String sharedKey : sharedKeys) { System.out.print("共享设备属性:" + sharedKey + " "); } } }catch (RuntimeException e) { throw new AdaptorException(e); } }
Example #2
Source File: ReSendMessageService.java From jmqtt with Apache License 2.0 | 6 votes |
public boolean dispatcherMessage(String clientId, Message message){ ClientSession clientSession = ConnectManager.getInstance().getClient(clientId); // client off line again if(clientSession == null){ log.warn("The client offline again, put the message to the offline queue,clientId:{}",clientId); return false; } int qos = (int) message.getHeader(MessageHeader.QOS); int messageId = message.getMsgId(); if(qos > 0){ flowMessageStore.cacheSendMsg(clientId,message); } MqttPublishMessage publishMessage = MessageUtil.getPubMessage(message,false,qos,messageId); clientSession.getCtx().writeAndFlush(publishMessage); return true; }
Example #3
Source File: ReSendMessageService.java From iot-mqtt with Apache License 2.0 | 6 votes |
public boolean dispatcherMessage(String clientId, Message message) { ClientSession clientSession = ConnectManager.getInstance().getClient(clientId); // client off line again if (clientSession == null) { log.warn("The client offline again, put the message to the offline queue,clientId:{}", clientId); return false; } int qos = (int) message.getHeader(MessageHeader.QOS); int messageId = message.getMsgId(); if (qos > 0) { flowMessageStore.cacheSendMsg(clientId, message); } MqttPublishMessage publishMessage = MessageUtil.getPubMessage(message, false, qos, messageId); clientSession.getCtx().writeAndFlush(publishMessage); return true; }
Example #4
Source File: GatewaySessionCtx.java From Groza with Apache License 2.0 | 6 votes |
public void onDeviceAttributes(MqttPublishMessage mqttMsg) throws AdaptorException { JsonElement json = validateJsonPayload(gatewaySessionId, mqttMsg.payload()); int requestId = mqttMsg.variableHeader().messageId(); if (json.isJsonObject()) { JsonObject jsonObj = json.getAsJsonObject(); for (Map.Entry<String, JsonElement> deviceEntry : jsonObj.entrySet()) { String deviceName = checkDeviceConnected(deviceEntry.getKey()); if (!deviceEntry.getValue().isJsonObject()) { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); } long ts = System.currentTimeMillis(); BasicAttributesUpdateRequest request = new BasicAttributesUpdateRequest(requestId); JsonObject deviceData = deviceEntry.getValue().getAsJsonObject(); request.add(JsonConverter.parseValues(deviceData).stream().map(kv -> new BaseAttributeKvEntry(kv, ts)).collect(Collectors.toList())); GatewayDeviceSessionCtx deviceSessionCtx = devices.get(deviceName); processor.process(new BasicTransportToDeviceSessionActorMsg(deviceSessionCtx.getDevice(), new BasicAdaptorToSessionActorMsg(deviceSessionCtx, request))); } } else { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); } }
Example #5
Source File: BrokerInterceptor.java From spring-boot-protocol with Apache License 2.0 | 6 votes |
@Override public void notifyTopicPublished(final MqttPublishMessage msg, final String clientID, final String username) { msg.retain(); executor.execute(() -> { try { int messageId = msg.variableHeader().messageId(); String topic = msg.variableHeader().topicName(); for (InterceptHandler handler : handlers.get(InterceptPublishMessage.class)) { LOG.debug("Notifying MQTT PUBLISH message to interceptor. CId={}, messageId={}, topic={}, " + "interceptorId={}", clientID, messageId, topic, handler.getID()); handler.onPublish(new InterceptPublishMessage(msg, clientID, username)); } } finally { msg.release(); } }); }
Example #6
Source File: GatewaySessionCtx.java From Groza with Apache License 2.0 | 6 votes |
public void onDeviceTelemetry(MqttPublishMessage mqttMsg) throws AdaptorException { JsonElement json = validateJsonPayload(gatewaySessionId, mqttMsg.payload()); int requestId = mqttMsg.variableHeader().messageId(); if (json.isJsonObject()) { JsonObject jsonObj = json.getAsJsonObject(); for (Map.Entry<String, JsonElement> deviceEntry : jsonObj.entrySet()) { String deviceName = checkDeviceConnected(deviceEntry.getKey()); if (!deviceEntry.getValue().isJsonArray()) { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); } BasicTelemetryUploadRequest request = new BasicTelemetryUploadRequest(requestId); JsonArray deviceData = deviceEntry.getValue().getAsJsonArray(); for (JsonElement element : deviceData) { JsonConverter.parseWithTs(request, element.getAsJsonObject()); } GatewayDeviceSessionCtx deviceSessionCtx = devices.get(deviceName); processor.process(new BasicTransportToDeviceSessionActorMsg(deviceSessionCtx.getDevice(), new BasicAdaptorToSessionActorMsg(deviceSessionCtx, request))); } } else { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); } }
Example #7
Source File: BrokerInterceptor.java From cassandana with Apache License 2.0 | 6 votes |
@Override public void notifyTopicPublished(final MqttPublishMessage msg, final String clientID, final String username) { msg.retain(); executor.execute(() -> { try { int messageId = msg.variableHeader().packetId();//messageId(); String topic = msg.variableHeader().topicName(); for (InterceptHandler handler : handlers.get(InterceptPublishMessage.class)) { LOG.debug("Notifying MQTT PUBLISH message to interceptor. CId={}, messageId={}, topic={}, " + "interceptorId={}", clientID, messageId, topic, handler.getID()); handler.onPublish(new InterceptPublishMessage(msg, clientID, username)); } } finally { ReferenceCountUtil.release(msg); } }); }
Example #8
Source File: JsonMqttAdaptor.java From iotplatform with Apache License 2.0 | 6 votes |
private FromDeviceMsg convertToGetAttributesRequest(DeviceSessionCtx ctx, MqttPublishMessage inbound) throws AdaptorException { String topicName = inbound.variableHeader().topicName(); try { Integer requestId = Integer .valueOf(topicName.substring(MqttTopics.DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX.length())); String payload = inbound.payload().toString(UTF8); JsonElement requestBody = new JsonParser().parse(payload); Set<String> clientKeys = toStringSet(requestBody, "clientKeys"); Set<String> sharedKeys = toStringSet(requestBody, "sharedKeys"); if (clientKeys == null && sharedKeys == null) { return new BasicGetAttributesRequest(requestId); } else { return new BasicGetAttributesRequest(requestId, clientKeys, sharedKeys); } } catch (RuntimeException e) { log.warn("Failed to decode get attributes request", e); throw new AdaptorException(e); } }
Example #9
Source File: JsonMqttAdaptor.java From IOT-Technical-Guide with Apache License 2.0 | 6 votes |
private static void convertToGetAttributesRequest(MqttPublishMessage inbound) throws AdaptorException { try { String payload = inbound.payload().toString(UTF8); JsonElement requestBody = new JsonParser().parse(payload); Set<String> clientKeys = toStringSet(requestBody, "clientKeys"); Set<String> sharedKeys = toStringSet(requestBody, "sharedKeys"); if (clientKeys == null && sharedKeys == null) { } else { for (String clientKey : clientKeys) { System.out.print("客户端属性:" + clientKey +" "); } for (String sharedKey : sharedKeys) { System.out.print("共享设备属性:" + sharedKey + " "); } } }catch (RuntimeException e) { throw new AdaptorException(e); } }
Example #10
Source File: SessionStore.java From WeEvent with Apache License 2.0 | 6 votes |
public boolean publishMessage(MqttPublishMessage msg, boolean will) { byte[] messageBytes = new byte[msg.payload().readableBytes()]; msg.payload().getBytes(msg.payload().readerIndex(), messageBytes); Map<String, String> extensions = new HashMap<>(); if (will) { extensions.put(WeEventConstants.EXTENSIONS_WILL_MESSAGE, WeEventConstants.EXTENSIONS_WILL_MESSAGE); } try { WeEvent event = new WeEvent(msg.variableHeader().topicName(), messageBytes, extensions); SendResult sendResult = this.producer.publish(event, "", this.timeout); return sendResult.getStatus() == SendResult.SendResultStatus.SUCCESS; } catch (BrokerException e) { log.error("exception in publish, {}", e.toString()); return false; } }
Example #11
Source File: JsonMqttAdaptor.java From IOT-Technical-Guide with Apache License 2.0 | 6 votes |
public static void convertToMsg(SessionMsgType type, MqttMessage inbound) throws AdaptorException { switch (type) { case POST_TELEMETRY_REQUEST: convertToTelemetryUploadRequest( (MqttPublishMessage) inbound); break; case POST_ATTRIBUTES_REQUEST: convertToUpdateAttributesRequest((MqttPublishMessage) inbound); break; case SUBSCRIBE_ATTRIBUTES_REQUEST: System.out.println("{\"key1\":\"value1\"}"); break; case GET_ATTRIBUTES_REQUEST: convertToGetAttributesRequest((MqttPublishMessage) inbound); break; } }
Example #12
Source File: Publish.java From WeEvent with Apache License 2.0 | 6 votes |
@Override public Optional<MqttMessage> process(MqttMessage req, String clientId, String remoteIp) throws BrokerException { MqttPublishMessage msg = (MqttPublishMessage) req; log.info("PUBLISH, {} Qos: {}", msg.variableHeader().topicName(), msg.fixedHeader().qosLevel()); switch (msg.fixedHeader().qosLevel()) { case AT_MOST_ONCE: { this.sessionStore.publishMessage(msg, false); return Optional.empty(); } case AT_LEAST_ONCE: { boolean result = this.sessionStore.publishMessage(msg, false); MqttQoS qos = result ? MqttQoS.AT_LEAST_ONCE : MqttQoS.FAILURE; MqttMessage rsp = MqttMessageFactory.newMessage(new MqttFixedHeader(MqttMessageType.PUBACK, false, qos, false, ProtocolProcess.fixLengthOfMessageId), MqttMessageIdVariableHeader.from(msg.variableHeader().packetId()), null); return Optional.of(rsp); } case EXACTLY_ONCE: default: { log.error("DOT NOT support Qos=2, close"); throw new BrokerException(ErrorCode.MQTT_NOT_SUPPORT_QOS2); } } }
Example #13
Source File: ConsumerProcess.java From ext-opensource-netty with Mozilla Public License 2.0 | 6 votes |
private void sendSubscribMessage(String clientId, Channel channel, MqttQoS respQoS, boolean bSavePubMsg, boolean bSend, BorkerMessage bMsgInfo) { if ((!bSavePubMsg) && (!bSend)) { return ; } String topicName = bMsgInfo.getTopicName(); boolean isDup = bMsgInfo.isDup(); boolean isRetain = bMsgInfo.isRetain(); byte[] msgBytes = bMsgInfo.getMsgBytes(); int bMsgId = getMustSendMessageId(respQoS, clientId); if (bSavePubMsg) { ConsumerMessage pubMsgObj = ConsumerMessage.builder().sourceClientId(clientId).topic(topicName) .mqttQoS(respQoS.value()).messageBytes(msgBytes).messageId(bMsgId).build(); consumerData.putPublishMessage(clientId, pubMsgObj); } if (bSend && channel != null) { MqttPublishMessage publishMessage = ProtocolUtil.publishMessage(topicName, isDup, respQoS.value(), isRetain, bMsgId, msgBytes); this.sendProcess.sendPublishMessage(channel, publishMessage); } }
Example #14
Source File: SubscribeProcessor.java From jmqtt with Apache License 2.0 | 5 votes |
private void dispatcherRetainMessage(ClientSession clientSession,List<Message> messages){ for(Message message : messages){ message.putHeader(MessageHeader.RETAIN,true); int qos = (int) message.getHeader(MessageHeader.QOS); if(qos > 0){ flowMessageStore.cacheSendMsg(clientSession.getClientId(),message); } MqttPublishMessage publishMessage = MessageUtil.getPubMessage(message,false,qos,clientSession.generateMessageId()); clientSession.getCtx().writeAndFlush(publishMessage); } }
Example #15
Source File: MQTTTestSupport.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Override public boolean intercept(MqttMessage packet, RemotingConnection connection) throws ActiveMQException { if (packet.getClass() == MqttPublishMessage.class) { messageCount++; } return true; }
Example #16
Source File: MemoryRetainedRepository.java From spring-boot-protocol with Apache License 2.0 | 5 votes |
@Override public void retain(Topic topic, MqttPublishMessage msg) { final ByteBuf payload = msg.content(); byte[] rawPayload = new byte[payload.readableBytes()]; payload.getBytes(0, rawPayload); final MqttRetainedMessage toStore = new MqttRetainedMessage(msg.fixedHeader().qosLevel(), rawPayload); storage.put(topic, toStore); }
Example #17
Source File: MQTTTestSupport.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Override public boolean intercept(MqttMessage packet, RemotingConnection connection) throws ActiveMQException { if (packet.getClass() == MqttPublishMessage.class) { messageCount++; } return true; }
Example #18
Source File: MemoryRetainedRepository.java From cassandana with Apache License 2.0 | 5 votes |
@Override public void retain(Topic topic, MqttPublishMessage msg) { final ByteBuf payload = msg.content(); byte[] rawPayload = new byte[payload.readableBytes()]; payload.getBytes(0, rawPayload); final RetainedMessage toStore = new RetainedMessage(msg.fixedHeader().qosLevel(), rawPayload); storage.put(topic, toStore); }
Example #19
Source File: MqttPacketReceiver.java From lannister with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) throws Exception { switch (msg.fixedHeader().messageType()) { case PUBLISH: if (receiver != null) { receiver.messageReceived(Message.newMessage(client.clientId(), (MqttPublishMessage) msg)); } int messageId = ((MqttPublishMessage) msg).variableHeader().messageId(); if (((MqttPublishMessage) msg).fixedHeader().qosLevel() == MqttQoS.AT_LEAST_ONCE) { client.send(MqttMessageFactory.puback(messageId)); } else if (((MqttPublishMessage) msg).fixedHeader().qosLevel() == MqttQoS.EXACTLY_ONCE) { client.send(MqttMessageFactory.pubrec(messageId)); } break; case CONNACK: sharedObject.receivedMessage(msg); synchronized (sharedObject.locker()) { sharedObject.locker().notify(); } break; case PUBREC: client.send(MqttMessageFactory.pubrel(((MqttMessageIdVariableHeader) msg.variableHeader()).messageId())); break; case SUBACK: case PUBACK: case PUBCOMP: default: break; } }
Example #20
Source File: SubscribeProcessor.java From iot-mqtt with Apache License 2.0 | 5 votes |
private void dispatcherRetainMessage(ClientSession clientSession,List<Message> messages){ for(Message message : messages){ message.putHeader(MessageHeader.RETAIN,true); int qos = (int) message.getHeader(MessageHeader.QOS); if(qos > 0){ flowMessageStore.cacheSendMsg(clientSession.getClientId(),message); } MqttPublishMessage publishMessage = MessageUtil.getPubMessage(message,false,qos,clientSession.generateMessageId()); clientSession.getCtx().writeAndFlush(publishMessage); } }
Example #21
Source File: SimpleMQTTInterceptor.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Override public boolean intercept(final MqttMessage mqttMessage, RemotingConnection connection) { System.out.println("MQTT control packet was intercepted " + mqttMessage.fixedHeader().messageType()); // If you need to handle an specific packet type: if (mqttMessage instanceof MqttPublishMessage) { MqttPublishMessage message = (MqttPublishMessage) mqttMessage; String originalMessage = message.payload().toString(Charset.forName("UTF-8")); System.out.println("Original message: " + originalMessage); // The new message content must not be bigger that the original content. String modifiedMessage = "Modified message "; message.payload().setBytes(0, modifiedMessage.getBytes()); } else { if (mqttMessage instanceof MqttConnectMessage) { MqttConnectMessage connectMessage = (MqttConnectMessage) mqttMessage; System.out.println("MQTT CONNECT control packet was intercepted " + connectMessage); } } // We return true which means "call next interceptor" (if there is one) or target. // If we returned false, it means "abort call" - no more interceptors would be called and neither would // the target return true; }
Example #22
Source File: SessionServiceImpl.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override public MqttPublishMessage getWillMessage(String clientId) { MqttSession session = localCache.get(clientId); if (null != session) { return session.getWillMessage(); } else { return null; } }
Example #23
Source File: MqttSession.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
public MqttSession(String clientId, Channel channel, boolean cleanSession, MqttPublishMessage willMessage) { super(channel); this.clientId = clientId; this.cleanSession = cleanSession; this.willMessage = willMessage; }
Example #24
Source File: MqttMessageSerializer.java From joyqueue with Apache License 2.0 | 5 votes |
public static BrokerMessage convertToBrokerMsg(Channel client, MqttPublishMessage mqttMessage) { BrokerMessage brokerMessage = new BrokerMessage(); long now = SystemClock.now(); final String clientId = NettyAttrManager.getAttrClientId(client); brokerMessage.setApp(clientId); brokerMessage.setTopic(mqttMessage.variableHeader().topicName()); brokerMessage.setCompressed(false); brokerMessage.setClientIp(IpUtil.toAddress(client.remoteAddress()).getBytes()); brokerMessage.setStartTime(now); brokerMessage.setSource(SourceType.MQTT.getValue()); brokerMessage.setBusinessId(Integer.toString(mqttMessage.variableHeader().packetId())); ByteBuf payload = mqttMessage.payload(); byte[] body = new byte[payload.readableBytes()]; int index = payload.readerIndex(); payload.readBytes(body); payload.readerIndex(index); brokerMessage.setBody(body); writeExtension(mqttMessage.fixedHeader().qosLevel(), brokerMessage); CRC32 crc32 = new CRC32(); crc32.update(brokerMessage.getBody().slice()); brokerMessage.setBodyCRC(crc32.getValue()); return brokerMessage; }
Example #25
Source File: MqttProtocolHandler.java From joyqueue with Apache License 2.0 | 5 votes |
public void processPublish(Channel client, MqttPublishMessage publishMessage) { String clientID = NettyAttrManager.getAttrClientId(client); if (Strings.isNullOrEmpty(clientID)) { LOG.error("ClientID is null or empty for publish, aborting... publishEvent message trace: <{}>", publishMessage.toString()); client.close().addListener(CLOSE_ON_FAILURE); return; } try { final String topic = publishMessage.variableHeader().topicName(); MqttConnection connection = connectionManager.getConnection(clientID); if (connection == null) { LOG.error("Client connection is null for publish, clientID: {}", clientID); client.close().addListener(CLOSE_ON_FAILURE); return; } String application = connection.getApplication(); if (Strings.isNullOrEmpty(application)) { LOG.error("Client application is null for publish, clientID: {}", clientID); client.close().addListener(CLOSE_ON_FAILURE); return; } Producer producer = producerManager.getProducer(clientID, application, topic); if (producer != null) { messagePublisher.publishMessage(producer, client, publishMessage); } else { throw new Exception("MessageProducer instance null, please check producer create & start..."); } } catch (Throwable th) { LOG.error("process Public Message Error!", th); client.close().addListener(CLOSE_ON_FAILURE); } }
Example #26
Source File: MQTTRejectingInterceptorTest.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Test(timeout = 60000) public void testRejectedMQTTMessage() throws Exception { final String addressQueue = name.getMethodName(); final String msgText = "Test rejected message"; final MQTTClientProvider subscribeProvider = getMQTTClientProvider(); initializeConnection(subscribeProvider); subscribeProvider.subscribe(addressQueue, AT_MOST_ONCE); MQTTInterceptor incomingInterceptor = new MQTTInterceptor() { @Override public boolean intercept(MqttMessage packet, RemotingConnection connection) throws ActiveMQException { if (packet.getClass() == MqttPublishMessage.class) { return false; } else { return true; } } }; server.getRemotingService().addIncomingInterceptor(incomingInterceptor); final MQTTClientProvider publishProvider = getMQTTClientProvider(); initializeConnection(publishProvider); publishProvider.publish(addressQueue, msgText.getBytes(), AT_MOST_ONCE, false); assertNull(subscribeProvider.receive(3000)); subscribeProvider.disconnect(); publishProvider.disconnect(); }
Example #27
Source File: ClientProtocolProcess.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
/** * B - S(Qos0, Qos1, Qos2) * @param channel * @param mqttMessage */ public void processPublish(Channel channel, MqttPublishMessage mqttMessage) { MqttFixedHeader mqttFixedHeader = mqttMessage.fixedHeader(); MqttPublishVariableHeader mqttPublishVariableHeader = mqttMessage.variableHeader(); ByteBuf payload = mqttMessage.payload(); String topciName = mqttPublishVariableHeader.topicName(); MqttQoS qosLevel = mqttFixedHeader.qosLevel(); int messageId = mqttPublishVariableHeader.packetId(); byte[] bytes = ByteBufUtil.copyByteBuf(payload); MessageData recviceMessage = MessageData.builder().topic(topciName).qos(qosLevel.value()) .messageId(messageId).payload(bytes) .status(MessageStatus.PUB) .dup(mqttFixedHeader.isDup()) .retained(mqttFixedHeader.isRetain()).build(); if (qosLevel == MqttQoS.EXACTLY_ONCE) { this.consumerProcess.saveMesage(recviceMessage); } this.consumerProcess.processPublish(recviceMessage); switch (qosLevel) { case AT_MOST_ONCE: break; case AT_LEAST_ONCE: this.consumerProcess.sendPubAckMessage(messageId); break; case EXACTLY_ONCE: this.consumerProcess.sendPubRecMessage(messageId); break; default: break; } }
Example #28
Source File: MqttClientHandler.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msgx) throws Exception { if (msgx == null) {return ;} MqttMessage msg = (MqttMessage) msgx; NettyLog.debug("read: {}", msg.fixedHeader().messageType()); MqttFixedHeader mqttFixedHeader = msg.fixedHeader(); switch (mqttFixedHeader.messageType()) { case CONNACK: clientProtocolProcess.processConnectBack(ctx.channel(), (MqttConnAckMessage) msg); break; case UNSUBACK: clientProtocolProcess.processUnSubBack(ctx.channel(), msg); break; case PUBLISH: clientProtocolProcess.processPublish(ctx.channel(), (MqttPublishMessage) msg); break; case PUBACK: clientProtocolProcess.processPubAck(ctx.channel(), msg); break; case PUBREC: clientProtocolProcess.processPubRec(ctx.channel(), msg); break; case PUBREL: clientProtocolProcess.processPubRel(ctx.channel(), msg); break; case PUBCOMP: clientProtocolProcess.processPubComp(ctx.channel(), msg); break; case SUBACK: clientProtocolProcess.processSubAck(ctx.channel(), (MqttSubAckMessage) msg); break; default: break; } }
Example #29
Source File: DefaultDispatcherMessage.java From iot-mqtt with Apache License 2.0 | 5 votes |
@Override public void run() { if (Objects.nonNull(messages)) { try { for (Message message : messages) { Set<Subscription> subscriptions = subscriptionMatcher.match((String) message.getHeader(MessageHeader.TOPIC)); for (Subscription subscription : subscriptions) { String clientId = subscription.getClientId(); ClientSession clientSession = ConnectManager.getInstance().getClient(subscription.getClientId()); if (ConnectManager.getInstance().containClient(clientId)) { int qos = MessageUtil.getMinQos((int) message.getHeader(MessageHeader.QOS), subscription.getQos()); message.putHeader(MessageHeader.QOS, qos); if (qos > 0) { flowMessageStore.cacheSendMsg(clientId, message); } MqttPublishMessage publishMessage = MessageUtil.getPubMessage(message, false, qos, message.getMsgId()); clientSession.getCtx().writeAndFlush(publishMessage); clientSession.addReceiveIdCounter();//收到一条 } else { offlineMessageStore.addOfflineMessage(clientId, message); } } } } catch (Exception ex) { log.warn("Dispatcher message failure,cause={}", ex); } } }
Example #30
Source File: MessageUtil.java From iot-mqtt with Apache License 2.0 | 5 votes |
public static MqttPublishMessage getPubMessage(Message message,boolean dup,int qos,int messageId){ MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH,dup,MqttQoS.valueOf(qos),false,0); MqttPublishVariableHeader publishVariableHeader = new MqttPublishVariableHeader((String) message.getHeader(MessageHeader.TOPIC),messageId); ByteBuf heapBuf; if(message.getPayload() == null){ heapBuf = Unpooled.EMPTY_BUFFER; }else{ heapBuf = Unpooled.wrappedBuffer((byte[])message.getPayload()); } return new MqttPublishMessage(fixedHeader,publishVariableHeader,heapBuf); }