user3808021
user3808021

Reputation:

EOFException when reading a url address

This is my code to read URL that sent from client:

(Server Class)

Socket serverS = serverSocket.accept();
DataInputStream in = new DataInputStream(serverS.getInputStream())

   if(in.readUTF().equals("http://localhost:8181")){
      // do something
      }

But it has an exception:

java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:340)
at java.io.DataInputStream.readUTF(DataInputStream.java:589)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at myp.T3Server.run(T3Server.java:37)

I write as UTF in client class.

update

client class:

        Socket client = new Socket(serverName, portNumber);
        OutputStream outToServer = client.getOutputStream();
        DataOutputStream out = new DataOutputStream(outToServer);
        out.writeInt("http://localhost:8181/pic");
        client.close();

server class:

   Socket serverS = serverSocket.accept();
   DataInputStream in = new DataInputStream(serverS.getInputStream());
     if (in.readUTF().equalsIgnoreCase("http://localhost:8181")) { 
         System.out.println("its http://localhost:8181");
           serverS.close();
         } else if (in.readUTF().equals("http://localhost:8181/pic")) {  //Error here
           System.out.println("its pic");
            serverS.close();
         }

Result:

java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:340)
at java.io.DataInputStream.readUTF(DataInputStream.java:589)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at myp.T3Server.run(T3Server.java:37)

Upvotes: 1

Views: 879

Answers (3)

laune
laune

Reputation: 31290

Apparently you expect one (1) String, but your code

  if (in.readUTF().equalsIgnoreCase("http://localhost:8181")) {    // !!!!!!
     System.out.println("its http://localhost:8181");
       serverS.close();
     } else if (in.readUTF().equals("http://localhost:8181/pic")) {  // !!!!!
       System.out.println("its pic");
        serverS.close();
     }

reads two (2) Strings if the first isn't the expected value. Do this:

String reply = in.readUTF();
if( "http://localhost:8181".equalsIgnoreCase( reply ) ||
    "http://localhost:8181/pic".equalsIgnoreCase( reply ) ){
    // success
} else {
    // failure
}
in.close();
// etc

Upvotes: 1

user3928077
user3928077

Reputation:

While reading from the file, your are not terminating your loop Throws:

EOFException - if this input stream reaches the end before reading eight bytes.

IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.

Upvotes: 0

lmo
lmo

Reputation: 547

A quick read on this: Class EOFException and you will probably figure out that the stream you're reading is empty.

Upvotes: 0

Related Questions