5

I am getting below EOFException while using readUTF() method, please let me know how could i overcome with this problem and also please suggest how readUTF() transfers socket information over the other networks

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

public class GreetingServer {
    public static void main(String args[]) {
        String servername =args[0];
        int port = Integer.parseInt(args[1]);

        try {
            System.out.println("Server Name "+ servername +"Port"+port);

            Socket client = new Socket(servername,port);
            System.out.println("Just connected to"+ client.getRemoteSocketAddress());
            OutputStream outs = client.getOutputStream();
            DataOutputStream dout = new DataOutputStream(outs);
            dout.writeUTF("Hello From"+client.getRemoteSocketAddress());
            InputStream in = client.getInputStream();
            DataInputStream din = new DataInputStream(in);
            System.out.println("Server Says"+ din.readUTF());
            client.close();
        }
        catch (EOFException f) {
            f.printStackTrace();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }
}
Laf
  • 7,965
  • 4
  • 37
  • 52
raja shekar
  • 61
  • 1
  • 1
  • 2
  • 1
    Show your server side code. The problem should be on server side which is sending incorrect/incomplete data – Tala Jul 31 '13 at 13:52

2 Answers2

8

You have reached the end of the stream. There is no more data to read.

Possibly your server isn't using writeUTF(), or you are out of sync with it. If the server is writing lines you should be using BufferedReader.readLine().

user207421
  • 305,947
  • 44
  • 307
  • 483
1

The docs for readUtf() state;

First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read. These bytes are then converted to characters by considering them in groups. The length of each group is computed from the value of the first byte of the group. The byte following a group, if any, is the first byte of the next group.

This suggests to me that what your trying to read with readUtf() isn't UTF, as the EOFException occurs when the End of File (EOF) is read unexpectedly.

Check that you are reading the right types in the same order that your server is sending them etc. You should be following a decided protocol, rather than blindly reading.

Robadob
  • 5,319
  • 2
  • 23
  • 32