DataInputStream读取不阻塞

时间:2017-07-20 01:34:39

标签: java sockets datainputstream

首先请原谅我,如果我误解了阻塞是如何工作的,我理解阻塞将暂停线程直到准备好,例如当读取用户输入时,程序将等到用户返回。

我的问题是,不是等待数据变得可用,而是读取值为0的字节。有没有办法阻止数据becoms可用?

方法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;
  }
}

1 个答案:

答案 0 :(得分:2)

如果read()返回-1,则对等方已断开连接。你不是在处理这种情况。如果检测到流结束,则必须关闭连接并停止读取。目前你无法这样做。您需要重新考虑您的方法签名。

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

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

相关问题