有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何读取数据输入流两次或两次以上?

我有一个到我在别处托管的应用程序的socket连接。一旦我连接了,我做了一个OutputStreamDataInputStream

连接完成后,我使用OutputStream向应用程序发送握手包。一旦这个握手被批准,它就会通过DataInputStream(1)返回一个数据包

这个数据包被处理并返回给应用程序,带有OutputStream

如果返回的数据有效,我从DataInputStream(2)中获得另一个数据包。然而,我无法通过DataInputStream阅读此数据包

我试图使用DataInputStream.markSupported()DataInputStream.mark(),但这没有给我任何帮助(除了一条空的异常消息)

是否可以再次读取输入流?如果是这样,有人能指出我做错了什么吗

编辑:以下是我的解决方案:

// First define the Output and Input streams.
OutputStream output = socket.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());

// Send the first packet to the application.
output.write("test"); // (not actual data that I sent)

// Make an empty byte array and fill it with the first response from the application.
byte[] incoming = new byte[200];
bis.read(incoming); //First packet receive

//Send a second packet to the application.
output.write("test2"); // (not actual data that I sent)

// Mark the Input stream to the length of the first response and reset the stream.
bis.mark(incoming.length);
bis.reset();

// Create a second empty byte array and fill it with the second response from the application.
byte[] incoming2 = new byte[200];
bis.read(incoming2);

我不确定这是否是最正确的方法,但这种方法对我很有效


共 (1) 个答案