NettyUdpClient.java 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package com.phm.netty.client;
  2. import java.net.InetSocketAddress;
  3. import org.springframework.stereotype.Component;
  4. import com.phm.common.exception.GlobalException;
  5. import com.phm.netty.client.handler.NettyUdpClientHandler;
  6. import io.netty.bootstrap.Bootstrap;
  7. import io.netty.buffer.Unpooled;
  8. import io.netty.channel.Channel;
  9. import io.netty.channel.ChannelInitializer;
  10. import io.netty.channel.ChannelOption;
  11. import io.netty.channel.EventLoopGroup;
  12. import io.netty.channel.nio.NioEventLoopGroup;
  13. import io.netty.channel.socket.DatagramPacket;
  14. import io.netty.channel.socket.nio.NioDatagramChannel;
  15. import io.netty.util.Attribute;
  16. import io.netty.util.AttributeKey;
  17. import lombok.extern.slf4j.Slf4j;
  18. /**
  19. * @Description NettyUdpClient
  20. * @Author WGK
  21. * @Date 2023/10/30 15:25
  22. */
  23. @Slf4j
  24. @Component
  25. public class NettyUdpClient {
  26. public void bind(String address, int port, byte[] data, String customValue) {
  27. EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
  28. try {
  29. Bootstrap clientBootstrap = new Bootstrap();
  30. clientBootstrap = clientBootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
  31. .option(ChannelOption.SO_BROADCAST, true).handler(new ChannelInitializer<NioDatagramChannel>() {
  32. @Override
  33. protected void initChannel(NioDatagramChannel ch) {
  34. // 使用 AttributeKey 定义一个键
  35. final AttributeKey<String> key = AttributeKey.valueOf("customKey");
  36. // 获取 Channel 的 Attribute
  37. Attribute<String> attr = ch.attr(key);
  38. // 设置自定义值
  39. attr.set(customValue);
  40. // 在这里添加你的处理器
  41. ch.pipeline().addLast(new NettyUdpClientHandler());
  42. }
  43. });
  44. Channel channel = clientBootstrap.bind(8989).sync().channel();
  45. // 给服务端发送请求信息
  46. channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(data), new InetSocketAddress(address, port)))
  47. .sync();
  48. // 方式一:查询等待超时 单位s, 超时自动关闭
  49. // channel.closeFuture().await(10000);
  50. // 方式er:原地等候返回消息,再关闭连接
  51. channel.closeFuture().sync();
  52. } catch (Exception e) {
  53. log.error(e.getMessage());
  54. throw new GlobalException("在线下载数据异常,请重新下载");
  55. } finally {
  56. log.info("netty client udp close!");
  57. eventLoopGroup.shutdownGracefully();
  58. }
  59. }
  60. // 测试
  61. public static void main(String[] args) {
  62. // 向网段内的所有机器广播UDP消息,这个没试过是不是这个原理
  63. // new BootNettyUdpClient().bind("255.255.255.255",9999,"I am client");
  64. // 指定某个套接字地址和发送的内容可以发送消息
  65. // 该方式也可以封装成一个udp的客户端的send类
  66. // new NettyUdpClient().bind("127.0.0.1", 9999, "I am client");
  67. }
  68. }