Java Socket 发送16进制心跳包

        最新对接硬件设备,需要给硬件连续发送16进制的数据心跳,让硬件知道有这么个连接,才能给我回调数据;代码如下;其中SocketUtil.java是本站另一个老大哥写的,但是找不到连接了,中间我又加了发送16进制格式的代码,可以直接用。

 SocketUtil.java

package com.rfid.util;

import com.util.DateUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;

/**
 * @ClassName: SocketUtil
 * @Author: 
 * @Date: 2023/01/03
 * @Description: TODO
 */

public class SocketUtil {

    final static String socketContent = "55 FF 15 FF FF FF 15 AA";

    private static final ThreadLocal<Socket> threadConnect = new ThreadLocal<Socket>();

    private static Socket client;

    private static OutputStream outStr = null;

    private static InputStream inStr = null;

    private static Thread tRecv = new Thread(new RecvThread());
    private static Thread tKeep = new Thread(new KeepThread());

    // 连接以及重新连接
    public static void connect(String host, int port) {
        try {
            client = threadConnect.get();
            if (client == null) {
                client = new Socket(host, port);
                threadConnect.set(client);
                tKeep.start();
                System.out.println("========链接开始!========");
            } else if (client.isClosed()) {
                client = new Socket(host, port);
                threadConnect.set(client);
                tRecv = new Thread(new RecvThread());
                tKeep = new Thread(new KeepThread());
                tKeep.start();
                System.out.println("========链接开始!========");
            }
            outStr = client.getOutputStream();
            inStr = client.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 断开连接
    public static void disconnect() {
        try {
            outStr.close();
            inStr.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 接收消息
    public static void receiveMsg() {
        tRecv.start();
    }

    // 发送消息
    public static void sendMsg(String msg) {
        try {
            byte[] bytes = hexStringToByteArray(msg);
            outStr.write(bytes);
            outStr.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class KeepThread implements Runnable {
        @Override
        public void run() {
            try {
                if (!client.getKeepAlive()) {
                    client.setKeepAlive(true);//true,若长时间没有连接则断开
                }
                if (!client.getOOBInline()) {
                    client.setOOBInline(true);//true,允许发送紧急数据,不做处理
                }
                if(!client.getTcpNoDelay()) {
                    client.setTcpNoDelay(true); // true , 不使用缓冲区
                }

                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("发送心跳数据包:" + DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                    /*outStr.write(socketContent.getBytes());
                    outStr.flush();*/
                    sendMsg(socketContent);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private static class RecvThread implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println("==============开始接收数据===============");
                while (true) {

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    byte[] b = new byte[1024];
                    if (inStr != null && inStr.available() > 0) {
                        int len = inStr.read(b);
                        String content = byteArrayToHexString(b, len);
                        System.out.println("接收数据 : " + content);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static String byteArrayToHexString(byte b[] , int len) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < len; i++){
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    public static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public static String byteToHexString(byte b) {
        int n = b;
        if (n < 0){
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * 16进制表示的字符串转换为字节数组
     *
     * @param hexString 16进制表示的字符串
     * @return byte[] 字节数组
     */
    public static byte[] hexStringToByteArray(String hexString){
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2){
            // 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
                    .digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

}

main方法

package com.test.sendHeart;

import java.io.UnsupportedEncodingException;

/**
 * @ClassName: SocketUtilTest
 * @Author:
 * @Date: 2023/01/03
 * @Description: TODO
 */

public class SocketUtilTest {


    public static void main(String[] args) {

        SocketUtil.connect("192.168.1.2",9099);
        // 发送16进制心跳数据包
        SocketUtil.sendMsg("55 FF 15 FF FF FF 15 AA");
        SocketUtil.receiveMsg();



    }

}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值