小码问答,有问必答!

为什么每次通过这个send方法只能发送一次数据,再发送就阻塞了

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();
        }
    }

}


JavaEE

收藏

暂无回答

我要回答