My app connects to a Wi-Fi peripheral. I’m using Socket.getInputStream() and Socket.getOutputStream() to read/write data. When the connection is established I store these two streams so that I can reuse them as long as I’m connected. My app sends a command via the OutputStream every second and reads the result from the InputStream by its read() method. After some time I get an "OutOfMemoryError".
Correct me if I’m wrong but I think this is because read() does not remove the read data from the InputStream, right?
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?
It seems not to be a problem with the OutputStream since I can call flush() for that.
What about reset() of InputStream? Does this remove the data for the stream?
Here is the code how I encapsulate my Streams:
@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;
}
}
The code for sending and receiving commands comes from this api:
The exception does also not come immediately. It occurs after ~30 Minutes and a lot of commands sent/received
whileis dodgy. If you reach the end of the stream before encountering a\n,-1is returned indefinitely and you have an infinite loop. If you allocate memory in the body of the loop (possibly in yourStringBuilderadding -1 over and over again) you will eventually run out of memory. It's only speculation because you're not showing the body of the loop.