CenterCommClientSender.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package com.its.cctv.xnetudp.thread;
  2. import com.its.cctv.xnetudp.codec.CenterCommClientEncoder;
  3. import io.netty.bootstrap.Bootstrap;
  4. import io.netty.channel.*;
  5. import io.netty.channel.nio.NioEventLoopGroup;
  6. import io.netty.channel.socket.nio.NioDatagramChannel;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.scheduling.annotation.Async;
  9. import org.springframework.stereotype.Service;
  10. import java.nio.ByteBuffer;
  11. @Slf4j
  12. @Service
  13. public class CenterCommClientSender {
  14. @Async("centerCommExecutor")
  15. public void run(String ip, int port, ByteBuffer sendBuffer) {
  16. if (sendBuffer == null) {
  17. log.error("CenterCommClientSender.run: Notify Data NULL");
  18. return;
  19. }
  20. EventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
  21. try {
  22. Bootstrap bootstrap = new Bootstrap();
  23. bootstrap.channel(NioDatagramChannel.class);
  24. bootstrap.group(nioEventLoopGroup);
  25. bootstrap.option(ChannelOption.SO_BROADCAST, false);
  26. bootstrap.handler(new ChannelInitializer<Channel>() {
  27. @Override
  28. protected void initChannel(Channel channel) throws Exception
  29. {
  30. channel.pipeline().addLast(new CenterCommClientEncoder(ip, port));
  31. }
  32. });
  33. Channel channel = bootstrap.bind(0).sync().channel();
  34. ChannelFuture f = channel.writeAndFlush(sendBuffer).sync();
  35. if (!f.isDone() || !f.isSuccess()) {
  36. log.error("CenterCommClientSender.run: Send Failed. isDone: {}, isSuccess: {}", f.isDone(), f.isSuccess());
  37. }
  38. }
  39. catch(Exception e) {
  40. log.error("CenterCommClientSender.run: Exception: {}", e.toString());
  41. e.printStackTrace();
  42. }
  43. finally {
  44. nioEventLoopGroup.shutdownGracefully();
  45. log.info("CenterCommClientSender.run: {} Bytes, ip: {}, port: {}", sendBuffer.array().length, ip, port);
  46. }
  47. }
  48. }