package com.its.api.xnetudp.codec; import com.its.api.utils.SysUtils; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.socket.DatagramPacket; import io.netty.handler.codec.MessageToMessageEncoder; import lombok.extern.slf4j.Slf4j; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.List; @Slf4j public class VmsServerRequestEncoder extends MessageToMessageEncoder { private String remoteIpAddr; private int remotePort; public VmsServerRequestEncoder(String hostIp, int hostPort) { this.remoteIpAddr = hostIp; this.remotePort = hostPort; } @Override protected void encode(ChannelHandlerContext ctx, Object msg, List out) throws Exception { Channel channel = ctx.channel(); if (!channel.isOpen()) { log.error("SEND: Channel Closed."); } if (!channel.isActive()) { log.error("SEND: Channel InActive."); channel.flush(); return; } if (!(msg instanceof ByteBuffer)) { log.error("SEND: Encoding Data source Unknown Type."); return; } int sendBytes = ((ByteBuffer) msg).array().length; if (this.remoteIpAddr == null) { log.error("SEND: [ERROR], RemoteAddress null, {} Bytes.", sendBytes); return; } else { log.info("SEND: [{}:{}], {} Bytes.", this.remoteIpAddr, this.remotePort, sendBytes); } log.info("SEND DUMP: {}", SysUtils.byteArrayToHex(((ByteBuffer) msg).array())); try { ByteBuf byteBuf = Unpooled.buffer(sendBytes); byteBuf.writeBytes(((ByteBuffer) msg).array()); InetSocketAddress addr = new InetSocketAddress(this.remoteIpAddr, this.remotePort); DatagramPacket packet = new DatagramPacket(byteBuf, addr); out.add(packet); } catch (Exception e) { log.error("SEND: [{}:{}], {} Bytes. Failed. Exception: {}", this.remoteIpAddr, this.remotePort, sendBytes, e.getMessage()); } } }