Disconnecting from a socket in java

Hi I am creating a small p2p program, implementing both the server and client side. When I have lunch for a client program, first think what it takes to connect to each server in its list, send data (about the client side) and disconnect. The next time the client side connects to one of these servers, it will be recognized.

My problem is when I tell the client side about disconnection, 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 disable i just wrote:

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

so how can i avoid this exception? thank!

+5
source share
3 answers

The JavaDoc for Socket.close () clearly states:

InputStream OutputStream.

, !

+10

, ?

, 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

Would it be correct to flash 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
source

All Articles