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!
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.
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.
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.