简体   繁体   中英

Receive Floats using java sockets from C++

I need to receive an array or a class containing floats from a c++ client to java server using sockets. But the InputStreamReader is not getting it right. Any reasons. Any suggestions for simpler ways would be appreciated. Thanks.

Java Server Code

public static void main(String[] args) throws IOException {
        // TODO code application logic here
         Values values=new Values();
         gui display=new gui();
         display.setVisible(true);
        ServerSocket Sock=new ServerSocket(9090);
        try{
            while(true){
                System.out.println("Waiting");
                Socket socket=Sock.accept();

                    System.out.println("Connected..");
                  InputStream ins=socket.getInputStream();
                    InputStreamReader insr= new InputStreamReader(ins);
                    BufferedReader br=new BufferedReader(insr);

                    byte[]Array=br.readLine().getBytes("UTF-8");
                   // values.SetValues(Array);


                    values.tWidth=Array[0];
                    values.waterLevel=Array[4];
                    values.camHeight=Array[8];
                    values.camViewAngleY=Array[12];
                    values.camViewAngleX=Array[16];
                    values.distFromCamBank=Array[20];
                    values.distTwoPoints=Array[24];
                    values.AvgVelocity=Array[28];
                    values.crossSecArea=Array[32];
                    values.Flow=Array[36];
                    values.camTiltAngle=Array[40];
                    values.aboveWater=Array[44];
                    System.out.println(values.tWidth);
                    System.out.println(values.waterLevel);
                    display.SetValues(values);
                    socket.close();
                }

        }
        finally{
            Sock.close();
        }


    }
}

I am storing those float in a Class called Values. But the values I get are junk. I am checking the values in C++ code before sending and they seem fine. Dont know where its going wrong. Please Help...!!

I suggest you try

DataInputStream ins = new DataInputStream(socket.getInputStream());
byte[] bytes = new bytes[48];
ins.readFuly(bytes);
ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder());

values.tWidth = bb.getFloat();
value.waterLevel = bb.getFloat();
// etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM