DataChannelUdpWithNio.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package org.ts.ddcs.net;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelOption;
  5. import io.netty.channel.EventLoopGroup;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.nio.NioDatagramChannel;
  8. import org.ts.ddcs.log.LogHelper;
  9. /**
  10. * UDP网络连接
  11. * @author dylan
  12. */
  13. public class DataChannelUdpWithNio {
  14. private String channelKey;
  15. private String bindAgreeement;
  16. private boolean nioChannelRunning = false;
  17. /*
  18. 监听端口
  19. */
  20. private int port = 0;
  21. private EventLoopGroup bossGroup = null;
  22. public DataChannelUdpWithNio(String key, String agreement){
  23. this.channelKey = key;
  24. this.bindAgreeement = agreement;
  25. }
  26. public DataChannelUdpWithNio colseChannel() {
  27. this.nioChannelRunning = false;
  28. if (null != bossGroup) {
  29. bossGroup.shutdownGracefully();
  30. bossGroup = null;
  31. }
  32. LogHelper.info("******************** 关闭 NIO ********************");
  33. return this;
  34. }
  35. public DataChannelUdpWithNio openChannel(int port) {
  36. this.nioChannelRunning = true;
  37. this.port = port;
  38. LogHelper.info("******************** 启动 NIO ********************");
  39. return this;
  40. }
  41. public void async() {
  42. if (!this.nioChannelRunning) {
  43. LogHelper.error("调用 Async() 发生错误:未打开通道");
  44. return;
  45. }
  46. new DataChannelUdpWithNio.AcceptThread().start();
  47. }
  48. private class AcceptThread extends Thread {
  49. @Override
  50. public void run() {
  51. bossGroup = new NioEventLoopGroup();
  52. try {
  53. Bootstrap b = new Bootstrap();
  54. b.group(bossGroup)
  55. .channel(NioDatagramChannel.class)
  56. .option(ChannelOption.SO_BROADCAST, true)
  57. .handler(new DatagramProverbServerHandler(channelKey,bindAgreeement));
  58. ChannelFuture f = b.bind(port).sync().channel().closeFuture().await();
  59. f.channel().closeFuture().sync();
  60. } catch (InterruptedException e) {
  61. LogHelper.error(e);
  62. } finally {
  63. if (null != bossGroup) {
  64. bossGroup.shutdownGracefully();
  65. }
  66. }
  67. }
  68. }
  69. }