Netty udp给指定客户端发消息

udp server

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

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


}

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Netty是一个高性能、异步事件驱动的网络应用程序框架,它支持多种传输协议,包括TCP、UDP、HTTP、WebSocket等。 下面是一个简单的Netty UDP客户端的示例代码: ```java public class UdpClient { public static void main(String[] args) throws Exception { // 创建 Bootstrap 对象 Bootstrap bootstrap = new Bootstrap(); // 设置 EventLoopGroup 对象 EventLoopGroup group = new NioEventLoopGroup(); try { // 配置 Bootstrap 对象 bootstrap.group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new UdpClientHandler()); // 绑定端口并启动客户端 Channel channel = bootstrap.bind(0).sync().channel(); // 发送数据 channel.writeAndFlush(new DatagramPacket( Unpooled.copiedBuffer("Hello, Netty UDP", CharsetUtil.UTF_8), new InetSocketAddress("255.255.255.255", 8080))).sync(); // 等待关闭 channel.closeFuture().await(); } finally { // 关闭 EventLoopGroup 对象 group.shutdownGracefully(); } } } class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> { @Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { // 接收到响应数据 ByteBuf buf = msg.content(); System.out.println(buf.toString(CharsetUtil.UTF_8)); } } ``` 此示例中,我们创建了一个Bootstrap对象,设置了NioEventLoopGroup和UDP通道,然后绑定端口并发送数据。我们还定义了一个UdpClientHandler类来处理接收到的响应数据。 在发送数据时,我们使用DatagramPacket对象指定要发送的数据和目标地址。在接收响应数据时,我们使用SimpleChannelInboundHandler类的channelRead0()方法来处理接收到的数据。 这只是一个简单的示例,你可以根据需要自定义Netty UDP客户端的行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值