简体   繁体   English

Android套接字写入中断读取

[英]android socket write interrupting read

Using android 2.3.3, I have a background Service which has a socket connection. 使用Android 2.3.3,我有一个具有套接字连接的后台服务。 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. 当我调用writeSocket时,write()不会引发异常,但是我看不到另一端的数据,并且在发生write()时,读取线程中的in.readLine()立即返回null。 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. 这将导致readwrite终止。 (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. (通常,因此也不例外。这就像尝试读取文件末尾一样。)您可以同时从不同的线程读取和写入数据,并且如果套接字关闭,无论正常还是异常,这两个操作都会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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