1
votes

Using android 2.3.3, I have a background Service which has a socket connection. There's a Thread that's reading from the socket continuously:

BufferedReader in = new BufferedReader(new InputStreamReader(mSock.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
    ... do stuff
}
// Socket has been closed (?)
in.close();

And then in my main thread I call:

private void writeSocket(String line) {
    mSock.getOutputStream().write(line.getData("US-ASCII"));
}

When I call writeSocket, the write() does not throw an exception but I don't see the data at the other end, and the in.readLine() in the reading thread immediately returns null when the write() occurs. From what I read, it should be safe to read and write simultaneously with the same socket from different threads? It seems like the write is causing the socket to close, but I don't get an exception..

1

1 Answers

1
votes

Most likely, the other end of the connection was closed normally. This causes both the read and write to terminate. (Normally, so no exception. It's just like trying to read past the end of a file.) You can read and write simultaneously from different threads and if the socket closes, whether normally or exceptionally, both operations will fail.