物联网 基于netty构建mqtt服务udp支持

物联网 基于netty构建mqtt服务udp支持

简述

应用中分别启动TCP和UDP两个服务,实现协议的分离与消息互通

源码

gitee.com/kcnf-iot/io...

代码

java 复制代码
package com.jysemel.iot;


import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;


public class DualProtocolServer {

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        EventLoopGroup udpGroup = new NioEventLoopGroup(); // UDP工作组

        try {
            // --- 1. MQTT over TCP 服务 (端口1883) ---
            ServerBootstrap tcpBootstrap = new ServerBootstrap();
            tcpBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new MqttDecoder(64 * 1024));
                            p.addLast(MqttEncoder.INSTANCE);
                            p.addLast("mqttHandler", new MqttServerHandler());  // MQTT业务逻辑
                        }
                    });
            ChannelFuture tcpFuture = tcpBootstrap.bind(1883).sync();
            System.out.println("[TCP] MQTT Broker 启动, 端口 1883");

            // --- 2. UDP 服务 (端口8888) 接收自定义传感器数据 ---
            Bootstrap udpBootstrap = new Bootstrap();
            udpBootstrap.group(udpGroup)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) {
                            ch.pipeline().addLast("udpHandler", new UdpServerHandler());
                        }
                    });
            ChannelFuture udpFuture = udpBootstrap.bind(8888).sync();
            System.out.println("[UDP] 自定义传感器服务启动, 端口 8888");

            tcpFuture.channel().closeFuture().sync();
            udpFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            udpGroup.shutdownGracefully();
        }
    }
}


package com.jysemel.iot;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.nio.charset.StandardCharsets;

public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        ByteBuf content = packet.content();
        String udpData = content.toString(StandardCharsets.UTF_8);
        System.out.println("[UDP] Received: " + udpData);

        // 将UDP数据转换为MQTT消息,并广播给所有MQTT客户端
        // 这里固定发布到 "udp/sensor" 主题
        MqttServerHandler.broadcast("udp/sensor", udpData);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("UDP error: " + cause.getMessage());
    }
}
相关推荐
JavaAgent架构师7 小时前
Spring AI接入OpenAI报错401/429?3种原因+完整解决代码
人工智能·后端
子兮曰7 小时前
AI Coding 为什么全选了 TUI?从 Claude Code 到 Codex CLI,终端架构的底层逻辑
前端·后端·ai编程
voyaqi7 小时前
从零设计企业级校验框架:Spring Boot + SPI 实战指南
spring boot·后端·log4j
XovH7 小时前
Django 从 0 到 1 打造完整电商平台:电商项目需求分析与数据库设计
后端
可乐泡枸杞7 小时前
《我用AI,一个月做出学了吗APP》
前端·人工智能·后端
huipeng9268 小时前
基于SpringCloud的博客系统
java·运维·后端·spring·spring cloud·微服务
神奇小汤圆8 小时前
一致性Hash算法:如何实现分布式系统中的高效数据分片?
后端
codealy8 小时前
Rust 核心理论与内存安全(一)
后端·安全·rust
小坏讲微服务8 小时前
SpringBoot整合SpringAI配置多平台API密钥
java·人工智能·spring boot·后端·flask·ai编程·claude code