|
@@ -0,0 +1,69 @@
|
|
|
+package com.phm.netty.client;
|
|
|
+
|
|
|
+import com.phm.netty.client.handler.NettyUdpClientHandler;
|
|
|
+import io.netty.bootstrap.Bootstrap;
|
|
|
+import io.netty.buffer.Unpooled;
|
|
|
+import io.netty.channel.Channel;
|
|
|
+import io.netty.channel.ChannelOption;
|
|
|
+import io.netty.channel.EventLoopGroup;
|
|
|
+import io.netty.channel.nio.NioEventLoopGroup;
|
|
|
+import io.netty.channel.socket.DatagramPacket;
|
|
|
+import io.netty.channel.socket.nio.NioDatagramChannel;
|
|
|
+import io.netty.util.CharsetUtil;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import java.net.InetSocketAddress;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @Description NettyUdpClient
|
|
|
+ * @Author WGK
|
|
|
+ * @Date 2023/10/30 15:25
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Component
|
|
|
+public class NettyUdpClient {
|
|
|
+ public void bind(String address, int port, String data) {
|
|
|
+ EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
|
|
|
+ try {
|
|
|
+ Bootstrap clientBootstrap = new Bootstrap();
|
|
|
+ clientBootstrap = clientBootstrap.group(eventLoopGroup);
|
|
|
+ clientBootstrap = clientBootstrap.channel(NioDatagramChannel.class);
|
|
|
+ clientBootstrap = clientBootstrap.option(ChannelOption.SO_BROADCAST, true);
|
|
|
+ clientBootstrap = clientBootstrap.handler(new NettyUdpClientHandler());
|
|
|
+ Channel channel = clientBootstrap.bind(0).sync().channel();
|
|
|
+ channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(data, CharsetUtil.UTF_8), new InetSocketAddress(address, port))).sync();
|
|
|
+ log.info("channel_id = {} ", channel.id().toString());
|
|
|
+
|
|
|
+ // 方式一:查询等待超时 单位s 等待服务端原路返回的消息,
|
|
|
+ // 在channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)方法中收到消息后可主动关闭channel,此处等待自然释放
|
|
|
+ channel.closeFuture().await(10000);
|
|
|
+
|
|
|
+ // 方式二:直接等待服务端原路返回后在
|
|
|
+ // channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)
|
|
|
+ // 方法中收到消息后可主动关闭channe
|
|
|
+ // 若服务端没有原路返回消息或者消息未收到将会一直等待,浪费资源
|
|
|
+ // channel.closeFuture().sync();
|
|
|
+
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error(e.getMessage());
|
|
|
+ } finally {
|
|
|
+ log.info("netty client udp close!");
|
|
|
+ eventLoopGroup.shutdownGracefully();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ // 测试
|
|
|
+ public static void main(String[] args) {
|
|
|
+
|
|
|
+ // 向网段内的所有机器广播UDP消息,这个没试过是不是这个原理
|
|
|
+ // new BootNettyUdpClient().bind("255.255.255.255",9999,"I am client");
|
|
|
+
|
|
|
+ // 指定某个套接字地址和发送的内容可以发送消息
|
|
|
+ // 该方式也可以封装成一个udp的客户端的send类
|
|
|
+ new NettyUdpClient().bind("127.0.0.1", 9999, "I am client");
|
|
|
+
|
|
|
+
|
|
|
+ }
|
|
|
+}
|