问题描述
我在客户端有这个代码:
I have this code on the client side :
DataInputStream dis = new DataInputStream(socketChannel.socket().getInputStream());
while(dis.available()){
SomeOtherClass.method(dis);
}
但不断返回 0
,尽管流中有可读数据。因此,在完成要读取的实际数据之后,空数据将被传递到另一个要读取的类,这会导致损坏。
But available()
keeps returning 0
, although there is readable data in the stream. So after the actual data to be read is finished, empty data is passed to the other class to be read and this causes corruption.
稍微搜索之后;我发现 available()
在使用套接字时不可靠,我应该从流中读取前几个字节,以实际查看数据是否可用于解析。
After a little search; I found that available()
is not reliable when using with sockets, and that I should be reading first few bytes from stream to actually see if data is available to parse.
但在我的情况下;我必须通过引用我从套接字到另一个我无法更改的类。
But in my case; I have to pass the DataInputStream
reference I get from the socket to some other class that I cannot change.
是否可以从 DataInputStream 没有破坏它或任何其他建议?
Is it possible to read a few bytes from DataInputStream
without corrupting it, or any other suggestions ?
推荐答案
放一个 PushbackInputStream 允许你读取一些字节而不用破坏数据。
Putting a PushbackInputStream in between allows you to read some bytes without corrupting the data.
编辑:下面未经测试的代码示例。这是来自内存。
Untested code example below. This is from memory.
static class MyWrapper extends PushbackInputStream {
MyWrapper(InputStream in) {
super(in);
}
@Override
public int available() throws IOException {
int b = super.read();
// do something specific?
super.unread(b);
return super.available();
}
}
public static void main(String... args) {
InputStream originalSocketStream = null;
DataInputStream dis = new DataInputStream(new MyWrapper(originalSocketStream));
}
这篇关于"购"来自Socket的DataInputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!