开发者

disconnecting from a socket in java

Hi i am building a little p2p program, implementing both the server-side and the client-side. when I lunch the client-side program, first think it does is to connect to each server in its list, send data (about the client-side) and disconnect. The next time the client-side 开发者_StackOverflow社区connects to one of these servers it will be recognized.

My problem - when i tell the client-side to disconnect, i get this exception

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)

to disconnect i just wrote:

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

so, how do i avoid this exception? thanks!


The JavaDoc for Socket.close() states clearly:

Closing this socket will also close the socket's InputStream and OutputStream.

which will throw the exception since you've already closed them!


When you close the client side, what would you expect to happen on the server side?

To avoid this exception, you need to implement you own readUnsignedShort() method like.

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);
}


Would it be right doing a flush before closing the output streams?:

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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜