gpt4 book ai didi

java - `BufferedInputStream.available()` 是否可以安全地获取已收到的字节?

转载 作者:可可西里 更新时间:2023-11-01 02:54:49 31 4
gpt4 key购买 nike

我想从 BufferedInputStream istream 接收一些数据,这些数据环绕着来自 Socket 的流。数据首先包含一个字节 n(8 位无符号整数),然后包含实际消息的 n 字节(二进制格式,而非字符串)。所以我写了如下代码(未测试):

public byte[] getNextMessageBytes() throws IOException {
// Make sure the "length" byte is ready to be read
if (this.istream.available() < 1) {
return null;
}

// Peek 1 byte
this.istream.mark(1);
int length = this.istream.read();

// -1 == EOF
if (length < 0) {
throw new EOFException();
}

// reset the marked byte
this.istream.reset();

// If all bytes available...
// NOTE the 'length' byte is still in the stream
if (this.istream.available() > length) {

// Peek the bytes...
this.istream.mark(length + 1);
// Skips the 'length' byte
this.istream.skip(1);

byte[] data = new byte[length];
int recv = this.istream.read(data, 0, length);
if (recv == length) {
this.istream.mark(0);
return data;
}
// -1 == EOF
if (recv < 0) {
throw new EOFException();
}
this.istream.reset();
}
return null;
}

这段代码基本上是先读取长度为n的字节。然后,如果 istream.available() 指示可用的完整长度,它将尝试读取一定数量的字节,如果成功,则返回字节数组。

docs of BufferedInputStream.available() :

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

“可以不阻塞地读取的字节数”可以解释为“套接字已经接收到的字节数”吗? istream.available() 实际上会返回一个少于 的数字,而不是已经收到的数据(即一些数据尚未发送到缓冲区)吗?

或者启动一个线程来阻止读取并将消息推送到队列/列表/vector/数组列表/等等实际上是一个更好的主意吗? (需要同步)

我的应用程序需要是实时的(充其量,但作为娱乐程序,毫秒级的一些延迟基本上是可以接受的),所以我很担心这一点。该程序大部分不完整,所以我还不能尝试。

最佳答案

Can "bytes that can be read without blocking" be interpreted as "bytes already received by the socket"?

这是唯一可以解释的方式。

Will istream.available() actually return a fewer number than the data that is already received (i.e. some data not yet sent to buffer)?

它可以返回从零开始的任何东西,即使是挂起的数据。在 SSLSockets 上它总是返回零。

但是您不需要调用它,也不需要所有复杂的代码。只需以阻塞模式读取流,并使用多线程。

关于java - `BufferedInputStream.available()` 是否可以安全地获取已收到的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14232306/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com