物联网 基于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());
    }
}
相关推荐
步行cgn16 小时前
YAML 的语法规则
spring boot·后端
骇客野人16 小时前
SpringBoot电商系统用户注册、登录、留存及数据埋点设计与落地实施方案
java·spring boot·后端
IT_陈寒19 小时前
React的状态更新坑得我差点加班到天亮
前端·人工智能·后端
码事漫谈20 小时前
一天搭出 80% 的 Agent,然后卡在 95% 到死
后端
leonkay20 小时前
C# 锁机制——【2】深入原理
开发语言·后端·spring·c#·个人开发
江湖十年20 小时前
在 Go 中使用 dyno 包处理动态对象
后端·面试·go
八角丶20 小时前
Node 网络编程 —— TLS 模块
javascript·后端·node.js
山岚的运维笔记21 小时前
mysql 专业笔记 -- 第 8 章:使用变量
运维·数据库·笔记·后端·学习·mysql·dba
平头哥AI1 天前
Day 01 | go run 跑通第一个 Go 程序,go build 留下一个能拷走的 exe
开发语言·后端·golang
ZGG0031 天前
线程池详解:从 7 大参数到生产避坑
java·数据库·后端