Socket通信 16进制 tcp 硬件交互

发布时间:2024年01月10日

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Socket通信 
 *https://www.jianshu.com/p/57954ec2cb68
 * https://blog.csdn.net/qq_39403545/article/details/84072739
 */
public class CabinetDoorUtils {
    public static final String open2 = "01 11 01 01 01 02 01 00 01 00 32 12 11";
    public static final String open3 = "01 11 01 01 01 02 01 00 01 00 32 12 11";
    public static final String open4 = "01 11 01 11 01 02 01 00 01 00 32 13 11";
    public static final String open5 = "01 11 01 11 01 02 01 00 01 00 32 13 11";
    public static final String open6 = "01 11 01 11 01 02 01 00 01 00 32 12 11";

    /**定时读取设备ID、DO、DI状态*/
    private static String heartbeat = "01 04 03 E8 00 14 70 75";

    private static Socket socket;

    private static int port;
    private static IReceiverMsg iReceiverMsg;


    public interface IReceiverMsg {
        void receiverMsg(String msg);

        void error(Exception e, String msg);
    }


    /**
     * "192.168.110.232", 10000
     * @param host 主机地址
     * @param port 端口
     * @param receiverMsg 接收消息
     */
    public static void connService(String host, int port, IReceiverMsg receiverMsg) {
        CabinetDoorUtils.port = port;
        iReceiverMsg = receiverMsg;
        new Thread(() -> {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                }
                socket = null;
            }
            try {
                System.out.println("connecting...");
                socket = new Socket(host, port);
                System.out.println("connection success");
                while (true) {
                    //输入流
                    InputStream in = socket.getInputStream();
                    if (socket.isClosed()) {
                        return;
                    }
                    //接收服务器的响应
                    byte[] buf = new byte[20];
                    //接收收到的数据
                    int len = in.read(buf);
                    String strReturn = BinaryToHexString(buf);
//                    System.out.println("接收数据:  " + strReturn);
                    iReceiverMsg.receiverMsg(strReturn);
                    heartbeatThread();
//                Thread.sleep(6000);
                }
            } catch (Exception e) {
                iReceiverMsg.error(e, "连接服务器失败,请重新连接");
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                        iReceiverMsg.error(e, null);
                    }
                }
            }
        }).start();
    }

    /**
     * 心跳线程
     */
    private static void heartbeatThread() {
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!socket.isConnected()) {
                    try {
                        socket.connect(new InetSocketAddress(CabinetDoorUtils.port));
                    } catch (IOException e) {
                        iReceiverMsg.error(e, "心跳重连服务器失败");
                    }
                }
                sendMsg(CabinetDoorUtils.heartbeat);
            }

        }).start();
    }

    /**
     * 发送的16进制字符串
     * @param cmd 命令
     */
    public static void sendMsg(String cmd) {
        try {
            System.out.println("发送数据: " + cmd);
            byte[] bytes = hexStringToByteArray(cmd);
            OutputStream os = socket.getOutputStream();
            os.write(bytes);
            os.flush(); // 刷新缓冲区,确保数据发送出去
        } catch (IOException e) {
            iReceiverMsg.error(e, "发送指令失败");
        }
    }


    /**
     * 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;
    }

    /**
     * 将字节数组转换成十六进制的字符串
     *
     * @return
     */
    public static String BinaryToHexString(byte[] bytes) {
        String hexStr = "0123456789ABCDEF";
        String result = "";
        String hex = "";
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result += hex + " ";
        }
        return result;
    }

}

另一个


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;

public class Client {

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

        Socket socket = null;
        try {
            System.out.println("connecting...");
            socket = new Socket("192.168.111.111", 1010);
            System.out.println("connection success");

            InputStream inputStream = socket.getInputStream();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        byte[] b = new byte[1024];
                        try {
                            inputStream.read(b);
                            String s = TmpUtils.bytesToHex(b);
                            System.out.println("s = " + s);
//                            System.out.println(new String());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            // 输入任意字符发送,输入q退出
            Scanner in = new Scanner(System.in);
            String str = "01 10 00 08 11 02 04 00 12 00 32 32 1D"; //发送的16进制字符串
            byte[] bytes = hexStringToByteArray(str);
            OutputStream os = socket.getOutputStream();
            while (!(in.nextLine()).equals("q")) { //输入q退出
                os.write(bytes);
            }
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) {

                }
            }
        }
    }

    /**
     * 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;
    }

文章来源:https://blog.csdn.net/xiaoerbuyu1233/article/details/135493962
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。