简体   繁体   中英

android socket write interrupting read

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..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM