【问题标题】:Java StreamCorruptedException invalid stream header when initializing every other time每隔一次初始化时,Java StreamCorruptedException 无效的流标头
【发布时间】:2013-06-25 22:55:08
【问题描述】:

编辑:我在这里上传了一些源代码:http://stabbedbit.com/MCapp/

我的流有问题,客户端每隔一段时间就会抛出 StreamCorruptedException。

例如:

first time: works fine -> exit client application.
second time: StreamCorruptedException -> exit client application.
third time: works fine -> exit client application.
forth time: StreamCorruptedException -> exit client application.

等等。

这是故事(简而言之)

服务器 while(true) 为客户端循环,接受它们,如果接受的客户端退出服务器的 inputStream 抛出一个套接字异常,我捕获并使用它来运行这个位代码:

if(dataSender   != null) dataSender.stop();
if(dataReceiver != null) dataReceiver.stop();

try { if(output  != null) output    .close(); } catch(IOException e) { streamNotClosed("output"); }
try { if(input   != null) input     .close(); } catch(IOException e) { streamNotClosed("input"); }
try { if(cryptOut!= null) cryptOut  .close(); } catch(IOException e) { streamNotClosed("encrypted output"); }
try { if(cryptIn != null) cryptIn   .close(); } catch(IOException e) { streamNotClosed("encrypted input"); }
try { if(clientSocket != null) clientSocket.close(); }
catch(IOException e){ logger.warning(socketNotClosed); }

似乎一切正常

客户端和服务器都使用这段代码来初始化流:

cryptOut = new CipherOutputStream(clientSocket.getOutputStream(), protocol.encoder);
output = new ObjectOutputStream(cryptOut);

cryptIn = new CipherInputStream(clientSocket.getInputStream(), protocol.decoder);
input = new ObjectInputStream(cryptIn);

如果一切顺利,一个字符串被交换为握手,用户得到验证,然后输入和输出被转发给单独的线程处理。

但是当它没有时,“input = new ObjectInputStream(cryptIn);”会引发以下错误

java.io.StreamCorruptedException: invalid stream header: 81C69F13
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
    at com.stabbedbit.minecraftRemoteAdmin.desktop.connection.ConnectionManager.run(ConnectionManager.java:89)
    at java.lang.Thread.run(Thread.java:722)

(每次抛出的代码(81C69F13)都不一样)

我尝试通过在停止线程和关闭流时调用垃圾收集器来解决这个问题。但它没有结果。而且我不知道为什么会发生这种情况。

编辑:如果我连接第二个客户端,我还发现我的服务器中断...

如果有人知道任何可以帮助我的事情,请提前致谢。

【问题讨论】:

  • 在读回数据之前尝试刷新输出流
  • "如果接受的客户端退出服务器的 inputStream 会抛出 Socket 异常"。等一下。它不应该那样做。抛出什么SocketException?什么信息?
  • @EJP 它抛出一个 EOFException 因为流在另一边被切断了。
  • @BimaleshJha 如何在初始化流之前刷新它?
  • @StabbedBit 在你写完flush() 流之后在你的输出流中。还要检查您的密码是否在您的代码中正确初始化/重置。

标签: java sockets exception inputstream


【解决方案1】:

完成写入后,在输出流中,flush() 流。此外,请检查您的密码是否在您的代码中正确初始化/重置

【讨论】:

    【解决方案2】:

    也许你需要关闭 ObjectOutputStream 代码; out.close();

    【讨论】:

    • 这无法解释为什么流标头无效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多