我需要和处理这种情况,我已经阅读了很多,但我还没有找到任何关于它的例子或文字。我有一个服务器套接字,它从 2 个客户端接收数据:a) 从发送压缩流的客户端。 b) 来自发送 ASCII 流的客户端。
a) 接收 Deflated 流:
inflater = new InflaterInputStream(clientSocket.getInputStream());
bout = new ByteArrayOutputStream(3025);
int b;
while ((b = inflater.read()) != -1) {
bout.write(b);
}
strMessage = new String(bout.toByteArray());
b) 从 ASCII 流接收:
bufferEnt = new char[3025];
Arrays.fill(bufferEnt,' ');
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
intLongBuffer = input.read(bufferEnt);
strMessage = new String(bufferEnt).trim();
在每种情况下,此代码都可以正常工作,并且变量 strMessage
具有正确的信息,但我需要确定流何时放气,何时不放气,以便我可以应用正确的部分每个案例的代码,这是我的大问题!
最佳答案
您可以将客户端套接字输入流包装到 BufferedInputStream
中,然后将缓冲流包装到 InflaterInputStream
中,然后尝试从 inflater 流中读取。如果出现错误,请忘记 inflater 流,倒回缓冲流,然后直接从缓冲流中读取。您必须使用缓冲流的 mark()
和 reset()
函数来倒回流,并且您可能必须尝试使用 mark( )
以确定要传递给它的值。类似于以下内容:
BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream());
bis.mark(1024); // experiment to find the correct value here
InflaterInputStream iis = new InflaterInputStream(bis);
try {
... // Process the inflated stream
} catch (ZipException ze) {
// It is not a ZIP stream. Try to process as text
bis.reset();
... // Process the text stream
}
关于java - 检测输入流是否放气,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16040640/