Java通过Jpcap 操作网路数据链路层对报文数据解析、监听网络数据包(服务器+客户端)

众所周知,Java语言虽然在TCP/UDP传输方面给予了良好的定义,但对于网络层以下的控制,却是无能为力的。JPCAP扩展包弥补了这一点。

     JPCAP实际上并非一个真正去实现对数据链路层的控制,而是一个中间件,JPCAP调用wincap/libpcap,而给JAVA语言提供一个公共的接口,从而实现了平台无关性。在官方网站上声明,JPCAP支持FreeBSD 3.x, Linux RedHat 6.1, Fedora Core 4, Solaris, and Microsoft windows 2000/XP等系统。

     使用Jpcap能做的事:

1.Jpcap是直接抓取经过数据链路层的数据包。 因此可以自己写IP数据包直接发送给数据链路层。

2.Jpcap会对抓取到的数据包进行一定程序的解析,根据数据包内容,将数据包封装为对应的对象()。

3.根据用户设定的信息,过滤数据包(其实就是在解析的时候,对不需要的数据直接丢弃,不解析)

4.Jpcap 只是直接从数据链路层上读取数据,并向数据链路层中发送数据,因此,Jpcap并不能操作 其他程序从数据链路层中读数据或者向网卡中发送数据。(IP层协议程序)

二话不说首先我们先上项目结构

所需要的jar包我已打包好

0、客户端  InfraredSensorClient.java

package com.airtimes.netty.network.client;


import com.airtimes.netty.network.client.handler.InfraredSensorClientHandler;

import io.netty.bootstrap.Bootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.ChannelOption;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioSocketChannel;


/**
 * 
 * 服务器持续监听宿主机的网卡信息、并时时返回报警中心协议在网卡中交换的数据
 * 客户端接收服务器端数据,打印出服务器送的消息
 * 
 */

public class InfraredSensorClient {

    public static void main(String[] args)
        throws Exception {

        // 创建EventLoopGroup线程池 Netty内部都是通过线程在处理数据
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 创建客户端连接基类 用于连接服务器
            Bootstrap bootstrap = new Bootstrap(); // (1)
            // 将 EventLoopGroup 加入线程池
            bootstrap.group(workerGroup); // (2)
            // 使用changlefactory 创建通信频道
            bootstrap.channel(NioSocketChannel.class); // (3)
            // Socket网路属性
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            // channel处理类
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                // 初始化channel
                @Override
                public void initChannel(SocketChannel channel)
                    throws Exception {

                    channel.pipeline().addLast(new InfraredSensorClientHandler());

                }

            });

            // Start the client.
            // 启动客户端
            ChannelFuture f = bootstrap.connect("127.0.0.1", 9090).sync(); // (5)

            // Wait until the connection is closed.
            // 等待连接关闭
            f.channel().closeFuture().sync();

        }
        finally {
            workerGroup.shutdownGracefully();
        }

    }
}

            1、客户端Handler  InfraredSensorClientHandler .java

package com.airtimes.netty.network.client.handler;


import java.io.IOException;

import com.airtimes.netty.network.response.Message;
import com.airtimes.netty.network.tools.Util;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;


public class InfraredSensorClientHandler extends ChannelInboundHandlerAdapter {

    private static final Util util = new Util();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        try {

            ByteBuf m = (ByteBuf)msg;
            String response = util.convertByteBufToString(m);
            System.out.println("收到来自服务器json信息: " + response + "\n");
            ObjectMapper objectMapper = new ObjectMapper();
            Message ClientMessage = objectMapper.readValue(response, Message.class);
            System.out.println("收到来自服务器对象信息: " + ClientMessage.toString() + "\n");

        }
        catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {

            ReferenceCountUtil.release(msg);

        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

           2、服务器端  InfraredSensorServer  .java

package com.airtimes.netty.network.server;


import com.airtimes.netty.network.server.handler.InfraredSensorServerHandler;

import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.ChannelOption;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioServerSocketChannel;

import io.netty.handler.timeout.ReadTimeoutHandler;

import io.netty.handler.timeout.WriteTimeoutHandler;


public class InfraredSensorServer {

    public static void main(String[] args) {

        // EventLoop 代替原来的 ChannelFactory

        EventLoopGroup bossGroup = new NioEventLoopGroup();

        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup)

                .channel(NioServerSocketChannel.class)

                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(

                            new InfraredSensorServerHandler(),

                            new WriteTimeoutHandler(10),

                            // 控制写入超时10秒构造参数10表示如果持续10秒钟都没有数据写了,那么就超时。

                            new ReadTimeoutHandler(10)

                );
                    }

                }).option(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = serverBootstrap.bind(9090).sync();

            f.channel().closeFuture().sync();

        }
        catch (InterruptedException e) {

        }
        finally {

            workerGroup.shutdownGracefully();

            bossGroup.shutdownGracefully();

        }

    }
}

     3、服务器端Handler  InfraredSensorServerHandler .java

package com.airtimes.netty.network.server.handler;


import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import com.airtimes.netty.network.response.Message;
import com.airtimes.netty.network.tools.TranscodingUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.packet.EthernetPacket;
import jpcap.packet.IPPacket;
import jpcap.packet.Packet;


public class InfraredSensorServerHandler extends ChannelInboundHandlerAdapter {

    private static final int caplen = 65535;

    private static final boolean promiscCheck = true;

    private static int f = 0;

    private static int i = 0;

    // ChannelHandlerContext通道处理上下文
    @Override
    public void channelActive(final ChannelHandlerContext ctx)
        throws InterruptedException,
        JsonProcessingException { // (1)

        // 第一步绑定网络设备
        NetworkInterface[] devices = JpcapCaptor.getDeviceList();
        for (NetworkInterface n : devices) {
            System.out.println("获取到本地网卡信息列表" + n.name + "     |     " + n.description);

        }
        System.out.println("-----------------------------------------------------------------");

        JpcapCaptor jpcap = null;

        try {
            jpcap = JpcapCaptor.openDevice(devices[2], caplen, promiscCheck, 50);
            // 指定筛选条件
            jpcap.setFilter("src 192.168.208.200 && len > 220 && len < 300 ", true);
            /* jpcap.setFilter("src 192.168.208.200 or 192.168.208.199  and len < 230 ",true); */
            // 0 或 1
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        // 第二步抓包
        while (true) {
            Packet packet = jpcap.getPacket();
            if (packet instanceof IPPacket && ((IPPacket)packet).version == 4) {
                
                i++ ;
                IPPacket ip = (IPPacket)packet;// 强转

                System.out.println("-------------------------------------第" + i + "次抓取数据包参数信息--------------------------------------------");

                System.out.println("版本:" + ip.version);
                System.out.println("优先权:" + ip.priority);
                System.out.println("区分服务:最大的吞吐量: " + ip.t_flag);
                System.out.println("区分服务:最高的可靠性:" + ip.r_flag);
                System.out.println("长度:" + ip.length);
                System.out.println("标识:" + ip.ident);
                System.out.println("DF:Don't Fragment: " + ip.dont_frag);
                System.out.println("NF:Nore Fragment: " + ip.more_frag);
                System.out.println("片偏移:" + ip.offset);
                System.out.println("生存时间:" + ip.hop_limit);

                String protocol = "";
                switch (new Integer(ip.protocol)) {
                    case 1:
                        protocol = "ICMP";
                        break;
                    case 2:
                        protocol = "IGMP";
                        break;
                    case 6:
                        protocol = "TCP";
                        break;
                    case 8:
                        protocol = "EGP";
                        break;
                    case 9:
                        protocol = "IGP";
                        break;
                    case 17:
                        protocol = "UDP";
                        break;
                    case 41:
                        protocol = "IPv6";
                        break;
                    case 89:
                        protocol = "OSPF";
                        break;
                    default:
                        break;
                }

                System.out.println("协议:" + protocol);
                System.out.println("源IP " + ip.src_ip.getHostAddress());
                System.out.println("目的IP " + ip.dst_ip.getHostAddress());
                /*
                 * System.out.println("源主机名: " + ip.src_ip); System.out.println("目的主机名: " + ip.dst_ip);
                 */
                TranscodingUtil transcodingUtil = new TranscodingUtil();
                String hexString = transcodingUtil.toHexString(ip.data);
                String hexStringToString = transcodingUtil.hexStringToString(hexString);

                String hexStringHead = transcodingUtil.toHexString(ip.header);
                String StringHead = transcodingUtil.hexStringToString(hexStringHead);

                /**********************
                 * 0-31
                 * ******************************************/
                String substring0 = hexString.substring(0, 32);
                System.out.println("0-31频段数据UTF_8 :" + transcodingUtil.hexStringToStringUTF(substring0));
                System.out.println("0-31频段数据GBK   :" + transcodingUtil.hexStringToStringGBK(substring0));
                System.out.println("0-31频段数据ISO   :" + transcodingUtil.hexStringToStringISO(substring0));
                System.out.println("0-31频段数据GB2312:" + transcodingUtil.hexStringToString(substring0));
                System.out.println("0-31频段数据BIG5  :" + transcodingUtil.hexStringToStringBIG(substring0));
                System.out.println("0-31频段数据UNICOD:" + transcodingUtil.hexStringToStringUNICODE(substring0));
                System.out.println("0-31频段数据十进制      :" + transcodingUtil.transcoding(substring0));
                System.out.println("0-31频段数据十六进制  :" + substring0);
                System.out.println("---------------------------------------------------------------------------------");

                /**********************
                 * 32-39 错误类型
                 * B7C0 C7F8 B8D0 D3A6 C6F7 B7C0 B2F0 BBD6 B8B4 防拆恢复
                 * ******************************************/
                String substring = hexString.substring(32, 40);
                System.out.println("32-39频段数据UTF_8 :" + transcodingUtil.hexStringToStringUTF(substring));
                System.out.println("32-39频段数据GBK   :" + transcodingUtil.hexStringToStringGBK(substring));
                System.out.println("32-39频段数据ISO   :" + transcodingUtil.hexStringToStringISO(substring));
                System.out.println("32-39频段数据GB2312:" + transcodingUtil.hexStringToString(substring));
                System.out.println("32-39频段数据BIG5  :" + transcodingUtil.hexStringToStringBIG(substring));
                System.out.println("32-39频段数据UNICOD:" + transcodingUtil.hexStringToStringUNICODE(substring));
                System.out.println("32-39频段数据十进制      :" + transcodingUtil.transcoding(substring));
                System.out.println("32-39频段数据十六进制  :" + substring);
                System.out.println("---------------------------------------------------------------------------------");

                /**********************
                 * 40-78
                 * B7C0 C7F8 B8D0 D3A6 C6F7 B7C0 B2F0 BBD6 B8B4 防拆恢复
                 * ******************************************/
                String substring6 = hexString.substring(40, 78);
                System.out.println("40-78频段数据UTF_8 :" + transcodingUtil.hexStringToStringUTF(substring6));
                System.out.println("40-78频段数据GBK   :" + transcodingUtil.hexStringToStringGBK(substring6));
                System.out.println("40-78频段数据ISO   :" + transcodingUtil.hexStringToStringISO(substring6));
                System.out.println("40-78频段数据GB2312:" + transcodingUtil.hexStringToString(substring6));
                System.out.println("40-78频段数据BIG5  :" + transcodingUtil.hexStringToStringBIG(substring6));
                System.out.println("40-78频段数据UNICOD:" + transcodingUtil.hexStringToStringUNICODE(substring6));
                System.out.println("40-78频段数据十进制      :" + transcodingUtil.transcoding(substring6));
                System.out.println("40-78频段数据十六进制  :" + substring6);
                System.out.println("---------------------------------------------------------------------------------");

                /**********************
                 * 79-103
                 * 
                 * ******************************************/
                String substring4 = hexString.substring(79, 103);
                System.out.println("79-103频段数据UTF_8 :" + transcodingUtil.hexStringToStringUTF(substring4));
                System.out.println("79-103频段数据GBK   :" + transcodingUtil.hexStringToStringGBK(substring4));
                System.out.println("79-103频段数据ISO   :" + transcodingUtil.hexStringToStringISO(substring4));
                System.out.println("79-103频段数据GB2312:" + transcodingUtil.hexStringToString(substring4));
                System.out.println("79-103频段数据BIG5  :" + transcodingUtil.hexStringToStringBIG(substring4));
                System.out.println("79-103频段数据UNICOD:" + transcodingUtil.hexStringToStringUNICODE(substring4));
                System.out.println("79-103频段数据十进制      :" + transcodingUtil.transcoding(substring4));
                System.out.println("79-103频段数据十六进制  :" + substring4);
                System.out.println("---------------------------------------------------------------------------------");

                /*********
                 104-119
                 * ************************************************/
                String substring2 = hexString.substring(104, 155);
                // 月份
                String month = hexString.substring(108, 110);
                String transmonth = transcodingUtil.transcoding(month);
                // 日份
                String day = hexString.substring(110, 112);
                String transday = transcodingUtil.transcoding(day);
                // 时间
                String hour = hexString.substring(112, 114);
                String transhour = transcodingUtil.transcoding(hour);
                // 分钟
                String min = hexString.substring(114, 116);
                String transmin = transcodingUtil.transcoding(min);

                // 秒
                String sec = hexString.substring(116, 119);
                Integer transec = null;
                if (Integer.parseInt(transcodingUtil.transcoding(sec)) > 6) {

                    transec = Integer.parseInt(transcodingUtil.transcoding(sec)) - 6;
                    System.err.println("D" + transec);
                }
                else {

                    transec = Integer.parseInt(transcodingUtil.transcoding(sec));
                    System.err.println("X" + transec);
                }

                System.out.println("104-119频段数据UTF_8 :" + transcodingUtil.hexStringToStringUTF(substring2));
                System.out.println("104-119频段数据GBK   :" + transcodingUtil.hexStringToStringGBK(substring2));
                System.out.println("104-119频段数据ISO   :" + transcodingUtil.hexStringToStringISO(substring2));
                System.out.println("104-119频段数据GB2312:" + transcodingUtil.hexStringToString(substring2));
                System.out.println("104-119频段数据BIG5  :" + transcodingUtil.hexStringToStringBIG(substring2));
                System.out.println("104-119频段数据UNICOD:" + transcodingUtil.hexStringToStringUNICODE(substring2));
                System.out.println("104-119频段数据拼接后时间序列:" + transmonth + "-" + transday + " " + transhour + ":"
                                   + transmin + ":" + transec);
                System.out.println("104-119频段数据十进制      :" + transcodingUtil.transcoding(substring2));
                System.out.println("104-119频段数据—月份      :" + transmonth + "月");
                System.out.println("104-119频段数据—日期      :" + transday + "日");
                System.out.println("104-119频段数据—小时      :" + transhour + "时");
                System.out.println("104-119频段数据—分钟      :" + transmin + "分钟");
                System.out.println("104-119频段数据— 秒       :" + transec + "秒");
                System.out.println("当前时间戳:" + System.currentTimeMillis());
                System.out.println("104-119频段数据十六进制  :" + substring2);
                System.out.println("---------------------------------------------------------------------------------");

                /*********
                 120-197
                * ************************************************/

                String substring5 = hexString.substring(120, 197);

                System.out.println("120-197频段数据UTF_8 :" + transcodingUtil.hexStringToStringUTF(substring5));
                System.out.println("120-197频段数据GBK   :" + transcodingUtil.hexStringToStringGBK(substring5));
                System.out.println("120-197频段数据ISO   :" + transcodingUtil.hexStringToStringISO(substring5));
                System.out.println("120-197频段数据GB2312:" + transcodingUtil.hexStringToString(substring5));
                System.out.println("120-197频段数据BIG5  :" + transcodingUtil.hexStringToStringBIG(substring5));
                System.out.println("120-197频段数据UNICOD:" + transcodingUtil.hexStringToStringUNICODE(substring5));
                System.out.println("120-197频段数据十进制      :" + transcodingUtil.transcoding(substring5));
                System.out.println("120-197频段数据十六进制  :" + substring5);
                System.out.println("---------------------------------------------------------------------------------");

                /*********
                 198-220
                 * ************************************************/
                String substring3 = hexString.substring(198, 310);
                System.out.println("198-+频段数据UTF_8 :" + transcodingUtil.hexStringToStringUTF(substring3));
                System.out.println("198-+频段数据GBK   :" + transcodingUtil.hexStringToStringGBK(substring3));
                System.out.println("198-+频段数据ISO   :" + transcodingUtil.hexStringToStringISO(substring3));
                System.out.println("198-+频段数据GB2312:" + transcodingUtil.hexStringToString(substring3));
                System.out.println("198-+频段数据BIG5  :" + transcodingUtil.hexStringToStringBIG(substring3));
                System.out.println("198-+频段数据UNICOD:" + transcodingUtil.hexStringToStringUNICODE(substring3));
                System.out.println("198-+频段数据十进制      :" + transcodingUtil.transcoding(substring3));
                System.out.println("198-+频段数据十六进制  :" + substring3);

                /*********
                                                  获取主机mac地址
                *************************************************/
                EthernetPacket datalink = (EthernetPacket)ip.datalink;
                StringBuffer srcMacStr = new StringBuffer();
                int count = 1;
                for (byte b : datalink.src_mac) {
                    String string = Integer.toHexString(b & 0xff);
                    if (string.length() == 1) {
                        string = "0" + string;
                    }
                    srcMacStr.append(string);
                    if (count++ != datalink.src_mac.length) srcMacStr.append(":");
                }
                System.out.println("获取主机mac地址为: " + srcMacStr);
                System.out.println("00:74:9c:e5:e0:01".equals(srcMacStr.toString()));

                /*********
                 *  数据汇总
                 *************************************************/
                
                
                
                String romateName ="3030315FB1A8BEAFD6F7BBFA";
                
                String transRomateName = transcodingUtil.hexStringToStringGBK(romateName);
                System.out.println(transRomateName);

                System.out.println("*************************数据汇总***************************************");

                System.out.println("数据包十六进制:" + hexString);
                System.out.println("数据包十六进制字符串数据包:" + hexStringToString);
                System.out.println("数据去向:" + ip.datalink);
                System.out.println("限制:" + ip.hop_limit);
                System.out.println("报文头十六进制:" + hexStringHead);
                System.out.println("报文头十进制:" + transcodingUtil.transcoding(hexStringHead));
                System.out.println("报文头十六进制字符串:" + StringHead);
                System.out.println("ip对象包:" + ip);
                /* System.err.println("报文头中时间戳序列 :"+transcodingUtil.stampToDate(ip.sec)); */
                /* System.out.println("ip对象包:"+ip.sec); */
                System.out.println("系统时间:" + new Date());
                
                f++ ;

                System.out.println("----------------------------本次抓取数据结束--累计" + f  + "---------------------------------------------------");
                System.out.println();

                /*********
                 *	将消息发送客户端汇总
                 *************************************************/
                Message message = new Message();
                message.setCurrentTime(new Date(System.currentTimeMillis()).toLocaleString());
                message.setEventDescription(transcodingUtil.hexStringToStringGBK(substring6).trim());
                message.setSystemCode(transcodingUtil.hexStringToStringGBK(substring));
                message.setEventId(UUID.randomUUID().toString());
                message.setSrcMac(srcMacStr.toString());
                
                ObjectMapper objectMapper = new ObjectMapper();
                String json = objectMapper.writeValueAsString(message);
                
                /*String test = transcodingUtil.hexStringToString(substring);*/
                ctx.writeAndFlush(Unpooled.wrappedBuffer(json.getBytes()));

            }
        }

    }

    @Override

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

        cause.printStackTrace();

        ctx.close();

    }
}

4、消息实体 Message.java

package com.airtimes.netty.network.response;

public class Message {
    
    /**
     * 事件id
     */
    private String eventId;
    
    /**
     * src_mac
     */
    
    private String srcMac;
    
    /**
     * 系统码
     */
    private String systemCode;
    
    /**
     * 事件描述
     */
    private String eventDescription;
    
    /**
     * 子系統
     */
    private Integer masterArea;
    
    /**
     * 防区
     */
    private Integer slaverId;
    
    /**
     * 事件时间
     */
    private String currentTime;

    public String getEventId() {
        return eventId;
    }

    public void setEventId(String eventId) {
        this.eventId = eventId;
    }

    public String getSystemCode() {
        return systemCode;
    }

    public void setSystemCode(String systemCode) {
        this.systemCode = systemCode;
    }

    public String getEventDescription() {
        return eventDescription;
    }

    public void setEventDescription(String eventDescription) {
        this.eventDescription = eventDescription;
    }

    public Integer getMasterArea() {
        return masterArea;
    }

    public void setMasterArea(Integer masterArea) {
        this.masterArea = masterArea;
    }

    public Integer getSlaverId() {
        return slaverId;
    }

    public void setSlaverId(Integer slaverId) {
        this.slaverId = slaverId;
    }

    public String getCurrentTime() {
        return currentTime;
    }

    public void setCurrentTime(String currentTime) {
        this.currentTime = currentTime;
    }

    public String getSrcMac() {
        return srcMac;
    }

    public void setSrcMac(String srcMac) {
        this.srcMac = srcMac;
    }

    @Override
    public String toString() {
        return "Message [eventId=" + eventId + ", srcMac=" + srcMac + ", systemCode=" + systemCode
               + ", eventDescription=" + eventDescription + ", masterArea=" + masterArea + ", slaverId=" + slaverId
               + ", currentTime=" + currentTime + "]";
    }

    
}

5、工具类转换 TranscodingUtil .java 

package com.airtimes.netty.network.tools;


import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;


public class TranscodingUtil {

    /**
     * 接收的byte包转换成16进制字符串
     * 
     * @param req
     * @return
     */
    public static String toHexString(byte[] req) {
        // 进行编码转译 byte --> hexString (字母大写)
        String str = "";
        for (int i = 0; i < req.length; i++ ) {
            String hex = Integer.toHexString(req[i] & 0xFF);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            str += hex.toUpperCase();
        }
        return str;
    }

    /**
     * 接收16进制字符串转换成10进制字符串
     * 
     * @param string
     * @return coding
     */
    public static String transcoding(String string) {

        // 传过来字符串的16进制字符个数
        int length = string.length() / 2;

        // 将字符串存进数组
        String[] s = new String[length];
        for (int i = 0; i < length; i++ ) {
            String ss = string.substring(i * 2, 2 + i * 2);
            s[i] = String.valueOf(ss);
        }

        // 定义接收转译之后的数组
        String[] str = new String[s.length];
        // 进行16进制向10进制转换
        for (int j = 0, k = s.length; j < k; j++ ) {
            str[j] = new BigInteger(s[j], 16).toString(10);
        }

        // 将转移后的数组转换为字符串
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length; i++ ) {
            sb.append(str[i]);
        }
        String coding = sb.toString();

        return coding;
    }

    /**
     * 16进制字符串转换为字符串
     *
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++ ) {
            try {
                baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "GB2312");
            new String();
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public static String hexStringToStringUTF(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++ ) {
            try {
                baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "utf-8");
            new String();
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public static String hexStringToStringGBK(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++ ) {
            try {
                baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");
            new String();
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public static String hexStringToStringISO(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++ ) {
            try {
                baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "GB18030");
            new String();
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public static String hexStringToStringBIG(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++ ) {
            try {
                baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "big5");
            new String();
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public static String hexStringToStringUNICODE(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++ ) {
            try {
                baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "unicode");
            new String();
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public static String[] bytesToHexStrings(byte[] src) {

        if (src == null || src.length <= 0) {

            return null;

        }

        String[] str = new String[src.length];

        for (int i = 0; i < src.length; i++ ) {

            String hex = Integer.toHexString(src[i] & 0xFF);
            if (hex.length() == 1) {

                hex = "0" + hex;
            }

            hex.join(",", str);

            /* string.Join(",", s); */
        }

        return str;

    }

    public static String toString(byte[] a) {
        if (a == null) return "null";
        int iMax = a.length - 1;
        if (iMax == -1) return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0;; i++ ) {
            b.append(a[i]);

            if (i == iMax) return b.append(']').toString();
            b.append(", ");
        }
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(Long s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

  public String convertByteBufToString(ByteBuf buf) {

        String str;

        if (buf.hasArray()) { // 处理堆缓冲区
            str = new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
        }
        else { // 处理直接缓冲区以及复合缓冲区
            byte[] bytes = new byte[buf.readableBytes()];
            buf.getBytes(buf.readerIndex(), bytes);
            str = new String(bytes, 0, buf.readableBytes());
        }
        return str;
    }

    public String Object2Json(Object obj) {
        JSONObject json = JSONObject.fromObject(obj);// 将java对象转换为json对象
        String str = json.toString();// 将json对象转换为字符串

        return str;
    }

}

6、运行结果:服务器端启动后台效果

 7、运行结果:客户端接收到服务器端报警信息

 8、运行结果:服务器端启动后台效果

 本文主要是对防区红外线设备、的报警信息通过报警主机之间通信截获报警数据、数据类型、防区报警、以及报警级别数据、进行捕捉解析转发、使用Netty Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序、当有客户端请求连接时、客户端将会收到服务器广播的异常信息、文中主要是以Json字符串类型、

 

本文出自 “想学Python的Java程序猿” 博客,请务必保留此出处郑重声明转载请注明原地址、谢谢https://blog.csdn.net/qq_37606336/article/details/85045785

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页