【发布时间】:2017-07-20 01:34:38
【问题描述】:
如果我误解了阻塞的工作原理,请原谅我,据我所知,阻塞会暂停线程直到它准备好,例如在读取用户输入时程序将等待用户点击返回。
我的问题是,它不是等待数据可用,而是读取值为 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;
}
}
【问题讨论】:
-
扩展
InputStream的流 将阻塞read参见 docs.oracle.com/javase/7/docs/api/java/io/…readFully也阻塞 - 也许服务器正在发送零 -
您必须在这里原谅我,因为这是我第一次使用套接字。我尝试使用以下内容作为阅读器,结果是相同的。 InputStream socketReaderStream = socket.getInputStream();
-
您对
read()的使用可能无法读取全部 4 个字节。您是不是要在那里使用readFully()来确保您读取所有4 个字节?read()的返回值是实际读取的字节数。 -
你的问题很好。
socketReaderStream是什么类型的对象? -
尝试更改为
int br = socketReader.read(rawLen); System.out.println ("Bytes read " + br);(用于调试)
标签: java sockets datainputstream