VmsServerRequestEncoder.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package com.its.api.xnetudp.codec;
  2. import com.its.api.utils.SysUtils;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.Channel;
  6. import io.netty.channel.ChannelHandlerContext;
  7. import io.netty.channel.socket.DatagramPacket;
  8. import io.netty.handler.codec.MessageToMessageEncoder;
  9. import lombok.extern.slf4j.Slf4j;
  10. import java.net.InetSocketAddress;
  11. import java.nio.ByteBuffer;
  12. import java.util.List;
  13. @Slf4j
  14. public class VmsServerRequestEncoder extends MessageToMessageEncoder<Object> {
  15. private String remoteIpAddr;
  16. private int remotePort;
  17. public VmsServerRequestEncoder(String hostIp, int hostPort) {
  18. this.remoteIpAddr = hostIp;
  19. this.remotePort = hostPort;
  20. }
  21. @Override
  22. protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
  23. Channel channel = ctx.channel();
  24. if (!channel.isOpen()) {
  25. log.error("SEND: Channel Closed.");
  26. }
  27. if (!channel.isActive()) {
  28. log.error("SEND: Channel InActive.");
  29. channel.flush();
  30. return;
  31. }
  32. if (!(msg instanceof ByteBuffer)) {
  33. log.error("SEND: Encoding Data source Unknown Type.");
  34. return;
  35. }
  36. int sendBytes = ((ByteBuffer) msg).array().length;
  37. if (this.remoteIpAddr == null) {
  38. log.error("SEND: [ERROR], RemoteAddress null, {} Bytes.", sendBytes);
  39. return;
  40. }
  41. else {
  42. log.info("SEND: [{}:{}], {} Bytes.", this.remoteIpAddr, this.remotePort, sendBytes);
  43. }
  44. log.info("SEND DUMP: {}", SysUtils.byteArrayToHex(((ByteBuffer) msg).array()));
  45. try {
  46. ByteBuf byteBuf = Unpooled.buffer(sendBytes);
  47. byteBuf.writeBytes(((ByteBuffer) msg).array());
  48. InetSocketAddress addr = new InetSocketAddress(this.remoteIpAddr, this.remotePort);
  49. DatagramPacket packet = new DatagramPacket(byteBuf, addr);
  50. out.add(packet);
  51. } catch (Exception e) {
  52. log.error("SEND: [{}:{}], {} Bytes. Failed. Exception: {}", this.remoteIpAddr, this.remotePort, sendBytes, e.getMessage());
  53. }
  54. }
  55. }