netty udp协议 硬件对接发送数据

netty udp协议 硬件对接发送数据

  1. 创建UDP服务
@Component
@Slf4j
@Order(5)
public class NettyUdpStart implements ApplicationRunner {

    /**
     * 启动netty服务
     *
     * @throws InterruptedException
     */
    private Bootstrap b;

    private EventLoopGroup bossGroup = null;

    private Channel channel;

    private Integer port;

    public void start() {
        if(SpringInitRunner.serverConfigDTOHashMap.get(ServerTypeEnum.TALKBACK_TERMINALS.getId())!=null){
            port=SpringInitRunner.serverConfigDTOHashMap.get(ServerTypeEnum.TALKBACK_TERMINALS.getId()).getPort();
        }else {
            return;
        }
        b = new Bootstrap();
        bossGroup = new NioEventLoopGroup(4);
        try {
            NetworkInterface ni = NetUtil.LOOPBACK_IF;
            InetAddress localAddress = null;
            localAddress=InetAddress.getByName(SpringInitRunner.fileDTO.getDefaultIP());
            b.group(bossGroup)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    // 设置LocalAddress
                    .localAddress(localAddress, port)
                    // 设置读缓冲区为 10M
                    .option(ChannelOption.SO_RCVBUF, 1024 * 1024 * 10)
                    // 设置写缓冲区为1M
                    .option(ChannelOption.SO_SNDBUF, 1024 * 1024 * 10)
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535))
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel nioDatagramChannel) throws Exception {
                            ChannelPipeline pipeline = nioDatagramChannel.pipeline();
                            pipeline.addLast(bossGroup, new UdpServerHandler());
                        }
                    });
            //开启需要监听 的端口
            ChannelFuture sync = b.bind(0);
            this.channel=sync.channel();
            log.info("启动成功:{}",port);
        } catch (Exception e) {
            log.error("启动异常", e);
        } finally {
//            bossGroup.shutdownGracefully();
        }


    }
    public void stop() {
        try {
            if (channel != null) {
                log.info("udp server is stopping listen port {} ...", port);
                channel.close();
                channel = null;
                log.info("udp server is stopped to listen port {} !", port);
            }
        } catch (Exception e) {
            log.error("close netty udp server exception", e);
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        start();
    }
}

  1. UdpServerHandler
@Component
@ChannelHandler.Sharable
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        // 将接收到的数据转为字符串,此字符串就是客户端发送的字符串
        ByteBuf buf =  msg.content();
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        String receiveStr = ConvertCode.receiveHexToString(bytes);
        System.err.println("客户端接收到消息:" + receiveStr);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();

    }

}
Netty是一个高性能、异步事件驱动的网络应用框架,特别适合用于构建高并发的服务器和客户端应用程序,包括UDP协议的支持。如果你想要在Netty中使用UDP进行多播(Multicast)通信,以下是一些关键步骤: 1. **创建MultiCastGroup**: 首先,你需要获取一个多播组地址,例如`InetAddress.getByName("224.0.0.1")`,这个例子是针对所有路由器组(Link-Local Multicast)。 2. **配置DatagramPacketFactory**: 创建一个`DatagramPacketFactory`实例,用于构建包含多播组信息的数据包。 ```java DatagramPacketFactory factory = new DefaultDatagramPacketFactory(); byte[] buffer = new byte[1024]; DatagramPacket packet = factory.newDatagram(buffer, buffer.length, multicastGroup); ``` 3. **设置SocketOptions**: 在`Bootstrap`或`ChannelInitializer`中,设置`DatagramChannel`的相关选项,如接收时间戳和多播组套接字计数器。 ```java ChannelConfig config = channel.config(); config.setOption(ChannelOption.SO_REUSEADDR, true); config.setOption(ChannelOption.SO_BROADCAST, true); config.setOption(ChannelOption.IP_MULTICAST_LOOP, true); // 发送时回环到本机 config.setOption(ChannelOption.IP_TTL, (short) 2); // 设置TTL值,通常2-3,防止无限传播 config.setOption(ChannelOption.IP_ADD_MEMBERSHIP, InetAddressUtil.getByName(multicastGroup.getHostAddress())); ``` 4. **创建Handler**: 编写一个处理多播数据包的处理器,比如`MulticastHandler`或自定义处理器。 5. **绑定端口并开始监听**: 最后,通过`Bootstrap`绑定端口并启动接受多播数据。 ```java Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(DatagramChannel.class) .handler(new MulticastHandler(packet)) .connect(multicastGroup.getPort()) .sync() .channel(); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值