1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package com.phm.netty.client;
- import java.net.InetSocketAddress;
- import org.springframework.stereotype.Component;
- import com.phm.common.exception.GlobalException;
- 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.ChannelInitializer;
- 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.Attribute;
- import io.netty.util.AttributeKey;
- import lombok.extern.slf4j.Slf4j;
- /**
- * @Description NettyUdpClient
- * @Author WGK
- * @Date 2023/10/30 15:25
- */
- @Slf4j
- @Component
- public class NettyUdpClient {
- public void bind(String address, int port, byte[] data, String customValue) {
- EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
- try {
- Bootstrap clientBootstrap = new Bootstrap();
- clientBootstrap = clientBootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
- .option(ChannelOption.SO_BROADCAST, true).handler(new ChannelInitializer<NioDatagramChannel>() {
- @Override
- protected void initChannel(NioDatagramChannel ch) {
- // 使用 AttributeKey 定义一个键
- final AttributeKey<String> key = AttributeKey.valueOf("customKey");
- // 获取 Channel 的 Attribute
- Attribute<String> attr = ch.attr(key);
- // 设置自定义值
- attr.set(customValue);
- // 在这里添加你的处理器
- ch.pipeline().addLast(new NettyUdpClientHandler());
- }
- });
- Channel channel = clientBootstrap.bind(8989).sync().channel();
- // 给服务端发送请求信息
- channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(data), new InetSocketAddress(address, port)))
- .sync();
- // 方式一:查询等待超时 单位s, 超时自动关闭
- // channel.closeFuture().await(10000);
- // 方式er:原地等候返回消息,再关闭连接
- channel.closeFuture().sync();
- } catch (Exception e) {
- log.error(e.getMessage());
- throw new GlobalException("在线下载数据异常,请重新下载");
- } 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");
- }
- }
|