Reputation: 1376
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
Upvotes: 1
Views: 1465
Reputation: 310859
Correct me if I’m wrong but I think this is because “read()” does not remove the read data from the InputStream, right?
Wrong. If you're running out of memory it's not because of InputStream. You have a bug in your code.
My question is: Is it a good practice to store the Streams?
Yes.
Or should I use “Socket.getInputStream(), Socket.getOutputStream() every time I send a new command?
No.
What about “reset()” of InputStream? Removes this the data for the stream?
No, it does what it says in the Javadoc.
EDIT The code you have linked to is at first inspection a load of rubbish. It never checks for end of stream for example, so when that happens it will read forever, accumulating 0xff bytes and eventually filling up memory. Find something better.
Upvotes: 3