Netty udp给指定客户端发消息

udp server

java 复制代码
package com.example.demo.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

/**
 * A UDP server that responds to the QOTM (quote of the moment) request to a {@link UdpClient}.
 * <p>
 * Inspired by <a href="https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html">the official
 * Java tutorial</a>.
 */
public final class UdpServer {

    private static final int PORT = Integer.parseInt(System.getProperty("port", "7686"));

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    // 设置读缓冲区为 10M
                    .option(ChannelOption.SO_RCVBUF, 1024 * 1024*10)
                    // 设置写缓冲区为1M
                    .option(ChannelOption.SO_SNDBUF, 1024 * 1024)
                    //解决最大接收2048个字节
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535))
                    .handler(new UdpServerHandler());

            b.bind(PORT).sync().channel().closeFuture().await();
        } finally {
            group.shutdownGracefully();
        }
    }
}

handler

java 复制代码
package com.example.demo.udp;

import com.google.common.collect.Maps;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Objects;


public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    public static Map<String, Channel> channelMap = Maps.newHashMap();

    @Override
    public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String msg = packet.content().toString(CharsetUtil.UTF_8);
        System.err.println("服务端接收消息:" + msg.length());
        System.err.println("服务端接收消息:" + msg);
        InetSocketAddress inetSocketAddress = packet.sender();
        System.out.println("---------" + inetSocketAddress.getHostString());
        System.out.println("==========" + inetSocketAddress.getPort());
        channelMap.put(inetSocketAddress.getHostString() + ":" + inetSocketAddress.getPort(), ctx.channel());
        ctx.channel().attr(AttributeKey.valueOf("deviceId")).setIfAbsent(inetSocketAddress.getHostString() + ":" + inetSocketAddress.getPort());
        //向指定客户端发消息
        Channel channel = channelMap.get("172.16.50.14:10010");
        if (Objects.nonNull(channel) && channel.isActive()) {
            InetSocketAddress ii = new InetSocketAddress("172.16.50.14",10010);
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("receice---- data", CharsetUtil.UTF_8),ii));
        }


    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        // We don't close the channel because we can keep serving requests.
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        //下线
        String id = (String) ctx.channel().attr(AttributeKey.valueOf("deviceId")).get();
        // map移除channel
        channelMap.remove(id);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        //有新的连接
        System.out.println(ctx.channel().remoteAddress().toString());
    }


}
相关推荐
辉视官方35 分钟前
2026深圳校园安全新方案 | SIP网络广播对讲系统,提升应急响应与智能教学水平
网络·安全
振浩微433射频芯片35 分钟前
告别“遥控失灵”:如何评估国产433芯片在智能家居领域的可靠性?
网络·单片机·嵌入式硬件·物联网·智能家居
pengyi87101539 分钟前
HTTP代理抓包核心原理,全面读懂请求与响应数据逻辑
网络·网络协议·http
云边云科技_云网融合1 小时前
@WAN SASE 1.0 全新起航,重新定义企业网络安全边界
网络·安全·web安全
小辰记事本1 小时前
从零读懂网卡内部架构:一条数据包的硬件之旅
网络·网络协议·架构·rdma
智慧光迅AINOPOL1 小时前
如何实现全光网的简单运维
网络·全光网解决方案·全光网·校园全光网·校园全光网解决方案
这是谁的博客?1 小时前
Python 异步编程核心原理与实践深度解析
java·网络·python·协程·asyncio·异步编程
2401_873479401 小时前
跨境电商如何评估用户IP真实性?用高精度IP地址查询+IP离线库实现
网络·tcp/ip·ip
minji...1 小时前
Linux 网络基础之网络IP层(十二)路由、路由表,分片和组装
linux·网络·tcp/ip·智能路由器·路由表·ip分片
Chengbei112 小时前
对标PentestGPT!新一代去中心化集群式AI全自动渗透测试工具
网络·人工智能·网络安全·去中心化·区块链·系统安全