Why DataInputStream.readUTF() causing Main Thread to wait forever ? [Socket Programming]

792 views Asked by At

I've got a little Socket Server that written in Java. My application basically reads data from Socket and writes it to the Output. Anyway when i'm trying to read data from Socket with readUTF() function it's just causing Main Thread to wait and then gives EOFException at the second connection but if i use DataInputStream.readLine() function it's working.

My code with readUTF() :

private static PrintStream console = System.out;

public static void main(String[] args) throws IOException{
    // TODO Auto-generated method stub
    ServerSocket serverSocket = new ServerSocket(5112);
    console.println("Server Started !");
    while(true){
        console.println("Loop");
        Socket client = serverSocket.accept();

        console.println("Processing Request");
        DataInputStream in = new DataInputStream(client.getInputStream());
        console.println("Proccessing in");
        console.println("Available : " + in.available());
        console.println("Request Body : \n");
        String str = in.readUTF(in);
        console.println(str);
        console.println("Waiting for new !");
    }
}

And the output is :

Server Started ! Loop Processing Request Proccessing in Available : 0 Request Body :

1

There are 1 answers

0
Zbynek Vyskovsky - kvr000 On

readUTF() reads binary encoded stream, not text data. Therefore the code expects probably thousands of characters due to the encoding.

See readUTF() documentation.