从零学Netty(九)Netty实现UDP服务器

我就是我 2022-12-15 06:12 290阅读 0赞

简介

  • UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议
  • UDP协议与TCP协议一样用于处理数据包,在OSI模型中,两者都位于传输层,处于IP协议的上一层
  • UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的
  • UDP用来支持那些需要在计算机之间传输数据的网络应用

实例demo

服务端实现

  1. /**
  2. * udp服务端
  3. *
  4. * @author LionLi
  5. */
  6. public class UdpServer {
  7. public static void main(String[] args) throws InterruptedException {
  8. EventLoopGroup group = new NioEventLoopGroup();
  9. try {
  10. Bootstrap bootstrap = new Bootstrap();
  11. bootstrap.group(group)
  12. // 主线程处理
  13. .channel(NioDatagramChannel.class)
  14. // 广播
  15. .option(ChannelOption.SO_BROADCAST, true)
  16. // 设置读缓冲区为2M
  17. .option(ChannelOption.SO_RCVBUF, 2048 * 1024)
  18. // 设置写缓冲区为1M
  19. .option(ChannelOption.SO_SNDBUF, 1024 * 1024)
  20. .handler(new ChannelInitializer<NioDatagramChannel>() {
  21. @Override
  22. protected void initChannel(NioDatagramChannel ch) {
  23. ChannelPipeline pipeline = ch.pipeline();
  24. pipeline.addLast(new NioEventLoopGroup(), new UdpServerHandler());
  25. }
  26. });
  27. ChannelFuture f = bootstrap.bind(8088).sync();
  28. System.out.println("服务器正在监听......");
  29. f.channel().closeFuture().sync();
  30. } finally {
  31. group.shutdownGracefully();
  32. }
  33. }
  34. }

服务端业务处理实现

  1. /**
  2. * 服务端业务处理
  3. *
  4. * @author LionLi
  5. */
  6. public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
  7. @Override
  8. protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
  9. System.out.println("服务端接收到消息:" + packet.content().toString(StandardCharsets.UTF_8));
  10. // 向客户端发送消息
  11. ByteBuf byteBuf = Unpooled.copiedBuffer("已经接收到消息!".getBytes(StandardCharsets.UTF_8));
  12. ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
  13. }
  14. }

客户端实现

  1. /**
  2. * udp客户端
  3. *
  4. * @author LionLi
  5. */
  6. public class UdpClient {
  7. public static void main(String[] args) {
  8. EventLoopGroup group = new NioEventLoopGroup();
  9. try {
  10. Bootstrap bootstrap = new Bootstrap();
  11. bootstrap.group(group)
  12. .channel(NioDatagramChannel.class)
  13. .handler(new ChannelInitializer<NioDatagramChannel>() {
  14. @Override
  15. protected void initChannel(NioDatagramChannel ch) {
  16. ChannelPipeline pipeline = ch.pipeline();
  17. pipeline.addLast(new UdpClientHandler());
  18. }
  19. });
  20. Channel channel = bootstrap.bind(8089).sync().channel();
  21. InetSocketAddress address = new InetSocketAddress("localhost", 8088);
  22. ByteBuf byteBuf = Unpooled.copiedBuffer("你好服务器".getBytes(StandardCharsets.UTF_8));
  23. channel.writeAndFlush(new DatagramPacket(byteBuf, address)).sync();
  24. channel.closeFuture().await();
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. } finally {
  28. group.shutdownGracefully();
  29. }
  30. }
  31. }

客户端业务处理

  1. /**
  2. * 客户端业务处理
  3. *
  4. * @author LionLi
  5. */
  6. public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
  7. //接受服务端发送的内容
  8. @Override
  9. protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
  10. System.out.println("客户端接收到消息:" + packet.content().toString(StandardCharsets.UTF_8));
  11. // 向客户端发送消息
  12. ByteBuf byteBuf = Unpooled.copiedBuffer("你好服务器".getBytes(StandardCharsets.UTF_8));
  13. ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
  14. }
  15. }

测试

分别启动服务端与客户端

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MDQ2MTI4MQ_size_16_color_FFFFFF_t_70

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MDQ2MTI4MQ_size_16_color_FFFFFF_t_70 1

项目已上传到gitee

地址: netty-demo

如果帮到您了,请帮忙点个star

发表评论

表情:
评论列表 (有 0 条评论,290人围观)

还没有评论,来说两句吧...

相关阅读

    相关 开始netty

    Netty概述: 1、netty是基于Java NIO的网络应用框架,client-server框架 2、Netty是一个高性能、异步事件驱动的NIO框架,它提供了对T