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());
    }


}
相关推荐
爱码小白21 分钟前
网络编程(王铭东老师)笔记
服务器·网络·笔记
蜜獾云31 分钟前
linux firewalld 命令详解
linux·运维·服务器·网络·windows·网络安全·firewalld
柒烨带你飞42 分钟前
路由器转发数据报的封装过程
网络·智能路由器
东方隐侠安全团队-千里1 小时前
网安瞭望台第17期:Rockstar 2FA 故障催生 FlowerStorm 钓鱼即服务扩张现象剖析
网络·chrome·web安全
神一样的老师2 小时前
面向高精度网络的时间同步安全管理架构
网络·安全·架构
与海boy3 小时前
CentOS7网络配置,解决不能联网、ping不通外网、主机的问题
linux·网络·网卡
我叫czc4 小时前
【python高级】342-TCP服务器开发流程
服务器·网络·tcp/ip
a_weng084 小时前
CS 144 check6: buiding an IP router
网络·网络协议·计算机网络
終不似少年遊*4 小时前
华为云计算HCIE笔记04
网络·华为云·云计算·学习笔记·hcie·认证·数据中心
红米饭配南瓜汤4 小时前
WebRTC服务质量(09)- Pacer机制(01) 流程概述
网络·音视频·webrtc