2011-04-26 122 views
5

嗨 我正在构建一个小的p2p程序,实现了服务器端和客户端。 当我午餐客户端程序时,首先想到的是连接到其列表中的每个服务器,发送数据(关于客户端)并断开连接。客户端下一次连接到其中一台服务器时,它将被识别。从java中断开连接

我的问题 - 当我告诉客户端断开连接,我得到这个例外

java.io.EOFException 
at java.io.DataInputStream.readUnsignedShort(Unknown Source) 
at java.io.DataInputStream.readUTF(Unknown Source) 
at java.io.DataInputStream.readUTF(Unknown Source) 
at oop.ex3.nameserver.NameServerThread.run(NameServerThread.java:24) 

断开我只是写:

finally { 
     out.close(); 
     in.close(); 
     socket.close(); 
    } 

那么,如何避免此异常?谢谢!

+0

呃之前做了刷新,你有没有想过,如果任何个人'接近()'语句抛出一个异常,会发生什么? – 2011-04-26 16:59:35

回答

10

为Socket.close的JavaDoc的()中明确规定:

关闭此套接字也将关闭 套接字的InputStream和OutputStream的 。

这将抛出异常,因为你已经关闭它们!

0

当您关闭客户端时,您希望在服务器端发生什么?

为避免此异常,您需要实现您自己的readUnsignedShort()方法。

public int readUnsignedShort() { 
    int ch1 = in.read(); 
    int ch2 = in.read(); 
    if ((ch1 | ch2) < 0) 
//  don't throw new EOFException(); 
     return -1; // EOF marker. 

    return (ch1 << 8) + (ch2 << 0); 
} 
0

难道是正确的关闭输出流?:

finally { 
    //this is the DataOutputStream 
    if(dout != null){ 
     dout.flush(); 
     dout.close(); 
    } 
    //and this the OutputStream 
    if(out != null){ 
     out.flush(); 
     out.close(); 
    } 
    if (din != null){ 
     din.close(); 
    } 
    if (in != null){ 
     in.close(); 
    } 
    if (socket != null){ 
     socket.close(); 
    } 
}