Question

I have a board that uses a modbus communication and I want create a connection with an android smartphone. With the jamod library it doesn't create the connection so I used a standard tcp socket. With this way I could create the connection and I can send a byte array to the board. The problem borns when I want read the board's reply.

This is the code:

byte[] asdo = {(byte)0x01, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0xff, (byte)0xff};

DataOutputStream scrittura = new DataOutputStream(socket.getOutputStream());

scrittura.flush();

scrittura.write(asdo);

scrittura.flush();

This code is into a thread that I call on the main. The reply of the board is a byte array like 'asdo' with six hex bytes.

How can I read the reply and convert it to a string so I can read?

Thanks!

Was it helpful?

Solution

Since you have byte[] data (array), there's a simple way of reading the data directly into a byte[].

InputStream stream = socket.getInputStream();
byte[] data = new byte[30];
int count = stream.read(data);

This would read this at once and return the number of occurences read.

OTHER TIPS

If you know the size of the expected reply in advance you should use DataInputStream.readFully(); otherwise DataInputStream.read(byte[]), which will return to you the number of bytes actually read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top