| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- 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<Object> {
- 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<Object> 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());
- }
- }
- }
|