DataInputStream 读不阻塞

DataInputStream read not blocking

首先,如果我误解了阻塞的工作原理,请原谅我,据我所知,阻塞将暂停线程直到它准备就绪,例如在读取用户输入时程序将等待直到用户点击 return .

我的问题是,它没有等待数据可用,而是读取值为 0 的字节。有没有办法阻塞直到数据可用?

在循环中调用方法 readBytes。

public byte[] readBytes(){
  try{

     //read the head int that will be 4 bytes telling the number of bytes that follow containing data
     byte[] rawLen = new byte[4];
     socketReader.read(rawLen);
     ByteBuffer bb = ByteBuffer.wrap(rawLen);
     int len = bb.getInt();

     byte[] data = new byte[len];
     if (len > 0) {
        socketReader.readFully(data);
     }

     return data;

  } catch (Exception e){
     e.printStackTrace();
     logError("Failed to read data: " + socket.toString());
     return null;
  }
}

如果read()返回-1,则对端已断开连接。你不是在处理那个案子。如果检测到流结束,则必须关闭连接并停止阅读。目前你没有办法这样做。您需要重新考虑您的方法签名。

你应该用readInt()代替那四行读取长度的代码。目前您假设已经读取了四个字节而没有实际检查。 readInt()会为您检查。

这样你也永远不会与发件人不同步,这在目前是一个严重的风险。