物联网 基于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());
    }
}
相关推荐
w139548564229 分钟前
鸿蒙原生开发手记:徒步迹 - 图片加载与缓存优化
后端
程序员爱钓鱼30 分钟前
Rust 数组 Array 详解:定义、访问、遍历与切片
后端·rust
前端工作日常10 小时前
我学习到的Java类和对象区别
java·后端
前端工作日常11 小时前
我学习到的Java类完整结构
java·后端
Csvn11 小时前
📊 SQL 入门 Day 6:多表查询 — JOIN 的四种姿势
后端·sql
hold?fish:palm13 小时前
RDB全量快照备份
c++·redis·后端
LucianaiB13 小时前
我把刘备一生做成了可播放的高德地图,还把整套方法封装成了 Skill
后端
Reart14 小时前
操作系统实验哈工大lab2——系统调用
后端·操作系统
IT_陈寒14 小时前
React useEffect依赖数组中埋的坑,这次终于让我逮到了
前端·人工智能·后端
扎Zn了老Fe14 小时前
MyBatis-Plus必知必会:告别低效CRUD,高效开发持久层
后端·mybatis