我有以下几行代码:
final int packetLength = 64 //just some constant
InputStream in = socket.getInputStream();
byte[] packet = new byte[packetLength];
int read = in.read(packet, 0, packetLength)
if(read != packetLength) {
//End of stream=
}
我能确定如果read(byte[], int, int)
没有返回与它应该读取的长度相同的值,那么流已经到达流的末尾吗?
因为下一个read()
调用应该返回-1
,不是吗?
不,你不能确定。InputStream
在读取您请求的所有数据之前不会进行阻塞——在读取一些数据之前会进行阻塞。(InputStream
的默认实现将读取,直到它能读取所有内容,但不能保证子类实现会这样做。)
您应该读取直到read
调用返回-1,或者如果您只想读取packetLength
字节:
byte[] packet = new byte[packetLength];
int offset = 0;
while (offset < packetLength) {
int bytesRead = in.read(packet, offset, packetLength - offset);
if (bytesRead == -1) {
// Incomplete packet - handle however you want to
}
offset += bytesRead;
}
// Hooray - read the complete packet.