while (true) {
byte[] buffer = new byte[1024];
InputStream input = socket.getInputStream();
bytes = input.read(buffer);
Log.d(TAG, "byte = " + bytes);
}
当我运行这段代码时,我可以在Log中看到只有bytes = 32
。
我的计划是显示整个数据,如"温度:26.7℃,湿度:40%"m,但我只能看到bytes=32
。
如何以原始形式显示接收到的数据?
阅读文档:
int read(byte[] b)
从输入流中读取一定数量的字节并将其存储到缓冲区数组b中。
如果您正在像这样阅读原始数据,那么您需要继续阅读直到bytes < 0
,因为这表明已经完成。
public static void main(String[] args) throws IOException {
byte[] buffer = new byte[1024];
InputStream input = socket.getInputStream();
int bytes = 0;
do {
bytes = input.read(buffer);
System.out.println("byte = " + new String(buffer));
} while (bytes > -1);
}
但更简单的是,如果你正在读取字符串并且只想要字符串数据,有一个更简单的方法:
public static void main(String[] args) throws IOException {
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
reader.lines().forEach(System.out::println);
}