物联网 基于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());
    }
}
相关推荐
骄马之死4 小时前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
GoGeekBaird5 小时前
Anthropic技能"(Skills)的经验分享
后端
王码码20355 小时前
多台服务器怎么统一看状态?Beszel 轻量监控,搭起来不费事
运维·服务器·后端·安全·阿里云·接口·web
郑洁文5 小时前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
指令集梦境7 小时前
Cursor + Spring Boot实战:从零写一个RESTful API
spring boot·后端·restful
码云之上7 小时前
聊聊如何设计一个高效、稳定的 Node.js 接入层
前端·后端·node.js
IT_陈寒8 小时前
Vite项目build后路由404了?你可能漏了这个小配置
前端·人工智能·后端
宸津-代码粉碎机9 小时前
Spring AI企业级实战|从RAG优化到Agent多工具调度
java·大数据·人工智能·后端·python·spring
吴佳浩9 小时前
AI Infra 的真相:Go 没输,rust也不是取代
后端·rust·go
喵个咪9 小时前
实时游戏网络协议深度对比:KCP vs WebRTC vs WebSocket
后端·websocket·webrtc