0

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!

Kerberos
  • 4,036
  • 3
  • 36
  • 55

2 Answers2

3

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.

nKn
  • 13,691
  • 9
  • 45
  • 62
  • The problem with this method is that I receive a strange reply, not what I expect and that I can see on a terminal. – Kerberos Feb 13 '14 at 20:01
  • Have you checked if these data is actually being sent *correctly*? – nKn Feb 13 '14 at 20:10
  • Don't know if it has something to do with it, but if you know how much `byte`s will be sent, you could adjust the array's size just to try. – nKn Feb 13 '14 at 20:39
  • 1
    @Kerberos The only 'problem' with this method is that it may not fill the buffer. You need to take note of the count it returns if it's less than the buffer size, and loop if necessary. Or see my answer. – user207421 Feb 13 '14 at 22:41
2

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.

user207421
  • 305,947
  • 44
  • 307
  • 483