硬件通信Java Socket怎么发送和接收16进制数据

Posted 汤姆猫丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了硬件通信Java Socket怎么发送和接收16进制数据相关的知识,希望对你有一定的参考价值。

关键点

  • 发送时:首先将你的16进制的数据,转化成byte[],然后发送

  • 接收时:获得数据,然后将byte[]的东西转化成16进制字符串

1 服务端socket

public class Server 

    private static class ClientHandler implements Runnable 

        private Socket socket;

        public ClientHandler(Socket socket) 
            this.socket = socket;
        

        @Override
        public void run() 

            try 

                //封装输入流(接收客户端的流)
                BufferedInputStream bis = new BufferedInputStream(
                        socket.getInputStream());
                DataInputStream dis = new DataInputStream(bis);
                byte[] bytes = new byte[1]; // 一次读取一个byte
                String ret = "";
                while (dis.read(bytes) != -1) 
                    ret += bytesToHexString(bytes) + " ";
                    if (dis.available() == 0)  //一个请求
                        System.out.println(socket.getRemoteSocketAddress() + ":" + ret);
                        ret = "";
                    
                

             catch (Exception e) 
                e.printStackTrace();
             finally 
                System.out.println("client is over");
                if (socket != null) 
                    try 
                        socket.close();
                     catch (IOException e) 

                        e.printStackTrace();
                    
                
            

        

    

    public static void main(String[] args) 

        ServerSocket server = null;
        try 
            server = new ServerSocket(8003);
            while (true) 
                System.out.println("listening...");

                Socket socket = server.accept();
                System.out.println("连接客户端地址:" + socket.getRemoteSocketAddress());
                System.out.println("connected...");
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();

            

         catch (Exception e) 
            e.printStackTrace();
         finally 

            if (server != null) 
                try 
                    server.close();
                 catch (IOException e) 

                    e.printStackTrace();
                
            
        
    

    /**
     * byte[]数组转换为16进制的字符串
     *
     * @param bytes 要转换的字节数组
     * @return 转换后的结果
     */
    public static String bytesToHexString(byte[] bytes) 
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) 
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) 
                sb.append('0');
            
            sb.append(hex);
        
        return sb.toString();
    

2 客户端socket

public class Client 

    public static void main(String[] args) 

        Socket socket = null;
        try 
            System.out.println("connecting...");
            socket = new Socket("127.0.0.1", 8003);
            System.out.println("connection success");

            // 输入任意字符发送,输入q退出
            Scanner in = new Scanner(System.in);
            String str = "01 10 00 00 00 02 04 00 01 00 00 a2 6f"; //发送的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;
    

 

以上是关于硬件通信Java Socket怎么发送和接收16进制数据的主要内容,如果未能解决你的问题,请参考以下文章

Java Socket通信之客户端程序 发送和接收数据

关于socket UDP通信,接收到乱码的问题!!急急急!SOS!

Java实现RS485串口通信,发送和接收数据进行解析

TCP通信实现对接硬件发送与接收十六进制数据 & int与byte的转换原理 & java中正负数的表示

Java 实例演示-ServerSocket 和 Socket 通信实例

socket 通信粘包怎么处理