CctvTcpServerEncoder.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package com.its.cctv.xnettcp.cctvserver.codec;
  2. import com.its.app.utils.NettyUtils;
  3. import com.its.cctv.config.RunningConfig;
  4. import com.its.cctv.entity.TbCctvCtlr;
  5. import com.its.cctv.global.AppRepository;
  6. import com.its.cctv.xnettcp.cctvserver.handler.CctvServerIdleStatePacketHandler;
  7. import io.netty.buffer.ByteBuf;
  8. import io.netty.channel.Channel;
  9. import io.netty.channel.ChannelHandler;
  10. import io.netty.channel.ChannelHandlerContext;
  11. import io.netty.handler.codec.MessageToByteEncoder;
  12. import lombok.RequiredArgsConstructor;
  13. import lombok.extern.slf4j.Slf4j;
  14. import org.slf4j.MDC;
  15. import org.springframework.stereotype.Component;
  16. @Slf4j
  17. @RequiredArgsConstructor
  18. @Component
  19. @ChannelHandler.Sharable
  20. public class CctvTcpServerEncoder extends MessageToByteEncoder<Object> {
  21. private final RunningConfig runningConfig;
  22. @Override
  23. protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf byteBuf) throws Exception {
  24. String ipAddress = NettyUtils.getRemoteIpAddress(ctx.channel());
  25. Channel channel = ctx.channel();
  26. TbCctvCtlr obj = AppRepository.getInstance().getCtlrIpMap().get(ipAddress);
  27. if (obj == null) {
  28. log.error("DsrcTcpServerEncoder.encode: Unknown Controller IP: {}. will be close.", ipAddress);
  29. CctvServerIdleStatePacketHandler.disconnectChannel(null, channel);
  30. return;
  31. }
  32. MDC.put("id", obj.getLogKey());
  33. if (obj.getChannel() != null && (channel != obj.getChannel())) {
  34. log.error("DsrcTcpServerEncoder.encode: {}, channel error, curr: {}, old: {}", ipAddress, channel.toString(), obj.getChannel().toString());
  35. CctvServerIdleStatePacketHandler.disconnectChannel(obj, channel);
  36. return;
  37. }
  38. if (!channel.isOpen() || !channel.isActive()) {
  39. log.error("DsrcTcpServerEncoder.encode: {}, isOpen: {}, isActive: {}. [{}]", ipAddress, channel.isOpen(), channel.isActive(), obj.getLogKey());
  40. CctvServerIdleStatePacketHandler.disconnectChannel(obj, channel);
  41. return;
  42. }
  43. }
  44. }