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.SneakyThrows; import java.net.InetSocketAddress; public class BootNettyUdpClient { private int port; private String server; public BootNettyUdpClient(String server,int port){ this.server = server; this.port = port; } @SneakyThrows public void send(String data) { data = AES.encryptAES(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 BootNettyUdpClientSimpleChannelInboundHandler()); Channel channel = clientBootstrap.bind(0).sync().channel(); channel.writeAndFlush(new DatagramPacket( Unpooled.copiedBuffer(data, CharsetUtil.UTF_8), new InetSocketAddress(server,port))); System.out.println("channnel id = "+channel.id().toString()); channel.closeFuture().await(); } catch (Exception e) { // TODO: handle exception } finally { System.out.println("netty client udp close!"); eventLoopGroup.shutdownGracefully(); } } }
暂无回答
我要回答