JAVA和C++通过socket发送和接收结构体

    xiaoxiao2021-03-25  90

    1、int、float字节转换

    /** * int转为低字节在前,高字节在后的byte数组 VC * @param n * @return byte[] */ private byte[] toLH(int n){ byte[] b = new byte[4]; b[0] = (byte) (n & 0xff); b[1] = (byte) (n >> 8 & 0xff); b[2] = (byte) (n >> 16 & 0xff); b[3] = (byte) (n >> 24 & 0xff); return b; } /** * 将float转为低字节在前,高字节在后的byte数组 * @param f * @return byte[] */ private byte[] toLH(float f) { return toLH(Float.floatToRawIntBits(f)); } public static byte[] intToByteArray(int i) throws Exception { ByteArrayOutputStream buf = new ByteArrayOutputStream(); DataOutputStream dos= new DataOutputStream(buf); dos.writeInt(i); byte[] b = buf.toByteArray(); dos.close(); buf.close(); return b; } public static int ByteArrayToInt(byte b[]) throws Exception { int temp = 0, a=0; ByteArrayInputStream buf = new ByteArrayInputStream(b); DataInputStream dis= new DataInputStream (buf); return dis.readInt(); }

    2、Java使用DataOutputStream发送对象

    (1)将C++结构体转化为对应的JAVA类

    C++定义的结构体:

    typedef struct { char szHead[4]; // 标志('H' 'E' 'A' 'D') DWORD dwSize; // 大小 }T_Head;

    对应的JAVA类:

    public class Head(){ private byte[] head; private int size; public Head(byte[] head,int size){ this.head = head; this.size = size; } public byte[] getHead(){ return this.head; } public int getSize(){ return this.size; } public void setHead(byte[] head){ this.head = head; } public void setSize(int size){ this.size = size; }

    (2)DataOutputStream发送数据

    DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.write(cmdHead.getHead()); out.write(toLH(cmdHead.getSize())); out.flush();

    (3) DataInputStream接收数据

    byte[] recvHead =newbyte[4]; int size; // readcmd转换字节序 socket.getInputStream().read(recvHead,0, 4); // read length转换字节序 socket.getInputStream().read(recvHead,0, 4); size = ByteArrayToInt(recvHead);
    转载请注明原文地址: https://ju.6miu.com/read-39791.html

    最新回复(0)