1. package cn.enjoyedu.udp.unicast;
    2. import io.netty.bootstrap.Bootstrap;
    3. import io.netty.buffer.Unpooled;
    4. import io.netty.channel.Channel;
    5. import io.netty.channel.EventLoopGroup;
    6. import io.netty.channel.nio.NioEventLoopGroup;
    7. import io.netty.channel.socket.DatagramPacket;
    8. import io.netty.channel.socket.nio.NioDatagramChannel;
    9. import io.netty.util.CharsetUtil;
    10. import java.net.InetSocketAddress;
    11. /**
    12. * 类说明:发送端
    13. */
    14. public class UdpQuestionSide {
    15. public final static String QUESTION = "告诉我一句古诗";
    16. public void run(int port) throws Exception{
    17. EventLoopGroup group = new NioEventLoopGroup();
    18. try {
    19. Bootstrap b = new Bootstrap();
    20. b.group(group)
    21. .channel(NioDatagramChannel.class)/*UDP通信*/
    22. .handler(new QuestoinHandler());
    23. Channel channel = b.bind(0).sync().channel();
    24. channel.writeAndFlush(
    25. new DatagramPacket(
    26. Unpooled.copiedBuffer(QUESTION,CharsetUtil.UTF_8),
    27. new InetSocketAddress("127.0.0.1",port)
    28. )
    29. ).sync();
    30. if(!channel.closeFuture().await(15000)){
    31. System.out.println("等待超时");
    32. }
    33. } catch (Exception e) {
    34. group.shutdownGracefully();
    35. }
    36. }
    37. public static void main(String [] args) throws Exception{
    38. new UdpQuestionSide().run(UdpAnswerSide.ANSWER_PORT);
    39. }
    40. }