提问人:Albert Cheng 提问时间:4/8/2016 最后编辑:Albert Cheng 更新时间:4/8/2016 访问量:509
我的 java 套接字程序在从 Eclipse 运行时提供 java.io.EOFException
My java socket program gives java.io.EOFException while running from Eclipse
问:
我正在运行一个 Java 套接字客户端。如果您第一次或前几次运行它,它就可以工作。但是,经过半天的调试,DataInputStream 读取 TCP 套接字的 readByte() 方法将抛出 java.io.EOFException。如果我重新启动 Eclipse,或者独立运行相同的 java 代码,完全没有问题。我想,这与Eclipse运行/调试Java代码的方式有关。不知何故,每次我们调试程序时都会使用一些资源,之后不会发布。有人知道吗?
代码如下
//DataInputStream is set outside of the scope.
DataInputStream dataInputStream;
StringBuffer stringBuffer = new StringBuffer();
while(true)
{
// java.io.EOFException is thrown at the line below.
byte c = dataInputStream.readByte();
if( c == 0) {
break;
}
stringBuffer.append( (char)c);
}
答:
-1赞
MrPublic
4/8/2016
#1
一般来说,out a (甚至一开始就有一个循环)不是一个好的做法。仅仅因为一个字节==0并不意味着你已经到达了数据流的末尾。你真的应该检查一下是否有更多的数据可以从流中读取,而不是假设读取一个空字节(在 Java 中为 0)(使用类似的东西)。一个简单的修复程序可能看起来像这样:break
while(true)
while(true)
available()
DataInputStream dataInputStream;
StringBuffer stringBuffer = new StringBuffer();
while(dataInputStream.available() > 0)
{
byte c = dataInputStream.readByte();
stringBuffer.append( (char)c);
}
这应该会继续将字符附加到 StringBuffer,并在达到 EoF 时停止。
评论
0赞
Albert Cheng
4/9/2016
这是没有意义的,因为这部分代码通常可以工作,它只会在 Eclipse 内部和运行半天后停止工作。
0赞
MrPublic
4/11/2016
@AlbertCheng 鉴于您发布的代码,这是我能想到的唯一解决方案。除了您遇到 EOF 异常之外,您的问题并没有解释太多,此答案试图解决该异常。
评论