gpt4 book ai didi

java - 从 InputStream 读取导致 OutOfMemoryError

转载 作者:行者123 更新时间:2023-11-29 05:01:18 24 4
gpt4 key购买 nike

我的应用连接到 Wi-Fi 外围设备。我正在使用 Socket.getInputStream()Socket.getOutputStream() 来读取/写入数据。建立连接后,我会存储这两个流,以便只要连接上就可以重用它们。我的应用程序每秒通过 OutputStream 发送一个命令,并通过其 read() 方法从 InputStream 读取结果。一段时间后,我得到一个“OutOfMemoryError”。如果我错了请纠正我,但我认为这是因为 read() 不会从 InputStream 中删除读取的数据,对吧?

我的问题是:存储流是一种好的做法吗?还是应该在每次发送新命令时都使用 Socket.getInputStream()Socket.getOutputStream()

这似乎不是 OutputStream 的问题,因为我可以为此调用 flush()InputStreamreset() 怎么样?这会删除流的数据吗?

这是我封装流的代码:

@Override
public InputStream getInputStream() throws IOException {
return _Socket.getInputStream();
}

@Override
public OutputStream getOutputStream() throws IOException {
return _Socket.getOutputStream();
}

@Override
public void connect() throws IOException {
try {
SocketAddress socketAddress = new InetSocketAddress(_ip, _port);

_Socket = new Socket(_ip, _port);
} catch (IOException e) {
MyExceptionHandler.appendLog(MyExceptionHandler.exceptionToString(e));

throw e;
}
}

发送和接收命令的代码来自这个api:

https://github.com/pires/obd-java-api/blob/master/src/main/java/com/github/pires/obd/commands/ObdCommand.java

异常也不会立即出现。它发生在 ~30 分钟后,发送/接收了大量命令

最佳答案

Correct me if I’m wrong but I think this is because “read()” does not remove the read data from the InputStream, right?

错了。如果内存不足,那不是因为 InputStream。您的代码中有错误。

My question is: Is it a good practice to store the Streams?

是的。

Or should I use “Socket.getInputStream(), Socket.getOutputStream() every time I send a new command?

没有。

What about “reset()” of InputStream? Removes this the data for the stream?

不,它按照 Javadoc 中的说明进行操作。

编辑 您链接到的代码起初是一堆垃圾。例如,它从不检查流的结尾,所以当发生这种情况时,它将永远读取,累积 0xff 字节并最终填满内存。找到更好的东西。

关于java - 从 InputStream 读取导致 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32029333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com