日期:2014-05-20  浏览次数:21194 次

程序报"java.io.EOFException"
在看网络基础编程,自己写了个程序,客户端给服务器端点对点对话,当输入bye的时候退出程序。
能实现相互对话了,但当不管服务器端或客户端谁输入bye都报异常。不知道哪里有问题??

服务器端程序:

import java.net.*;
import java.io.*;

public class Test07 {
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(6666);
String str = null;
String zs = null;
while(true){
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if((str=dis.readUTF())!=null){
System.out.println("客户端说:" + str);
}
while(!((zs=br.readLine()).equals("bye"))){
dos.writeUTF(zs);
dos.flush();
System.out.println("等待客户器端说话...");
if((str=dis.readUTF())!=null){
System.out.println("客户端说:" + str);
}
}
br.close();
dos.close();
dis.close();
s.close();

}
}catch(IOException e){
e.printStackTrace();
}
}
}


客户端程序:

import java.net.*;
import java.io.*;

public class Test08 {
public static void main(String[] args){
try{
String str = null;
String zs = null;
Socket s = new Socket("127.0.0.1",6666);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

while(!((zs=br.readLine()).equals("bye"))){
dos.writeUTF(zs);
os.flush();
System.out.println("等待服务端说话...");
if((str=dis.readUTF())!=null){
System.out.println("服务端说:" + str);
}
}
s.close();
br.close();
dos.close();
dis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}


报的错误:
java.io.EOFException
        at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:323)
        at java.io.DataInputStream.readUTF(DataInputStream.java:572)
        at java.io.DataInputStream.readUTF(DataInputStream.java:547)
        at Test07.main(Test07.java:15)

麻烦了
------解决方案--------------------
public final String readUTF()
                     throws IOException
See the general contract of the readUTF method of DataInput. 
Bytes for this operation are read from the contained input stream. 


Specified by:
readUTF in interface DataInput 
Returns:
a Unicode string. 
Throws: 
EOFException - if this input stream reaches the end before reading all the bytes.
 
IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs. 
UTFDataFormatException - if the bytes do not represent a valid modified UTF-8 encoding of a string.
See Also:
readUTF(java.io.DataInput)


这问题确实很蛋疼,貌似是个bug,不建议用readutf这个方法