Carven
Carven

Reputation: 15660

Socket gets stuck when doing readLine()

I am trying to connect to the POP server through Sockets in Java. I did the following code to run a LIST command to list all the emails from the server. But I don't know why on the second readLine() to read the second line and onwards, my application hangs at there.

popSock = new Socket(mailHost, pop_PORT);
inn = popSock.getInputStream();
outt = popSock.getOutputStream();
in = new BufferedReader(new InputStreamReader(inn));
out = new PrintWriter(new OutputStreamWriter(outt), true);

//USER and PASS commands to auth the server are ok

out.println("LIST");
String response = in.readLine();
System.out.println(response);

//Attempt to read the second line from the buffer but it hangs at here.
response = in.readLine();
System.out.println(response);

On the second in.readLine(), the application gets stuck at here and doesn't proceed from here. When I run the LIST command on telnet, I get the whole list of emails. So I should get the same response from the socket but I am not. How should I read the whole response line by line from the server?

Upvotes: 1

Views: 11717

Answers (4)

Snehal Indurkar
Snehal Indurkar

Reputation: 79

You can try following--

    try {
        String line = inn.readLine();
        while(***input.ready()***)
        {
            System.out.println(line);
            line=inn.readLine();

        }
        inn.close();


    } catch (IOException e) {

        e.printStackTrace();
    }

where inn is your bufferedReader object whih stores the inputstreamdata

Upvotes: -1

Uffe
Uffe

Reputation: 10514

readLine() won't return until it's read a carriage return or a line feed, which is what you normally get when you read from a terminal or a text file.

I wouldn't be surprised if the POP server doesn't actually tack \r\n on the end of its messages. Try read() instead.

Upvotes: 6

Jagat
Jagat

Reputation: 1402

Try reading it one character at a time using in.read and printing it. Perhaps, there's an issue with the newline character that the server is sending.

Upvotes: -1

Rocky Pulley
Rocky Pulley

Reputation: 23321

You should be sending \r\n after each command, also, try not using a BufferedInputStream, try reading directly from the InputStream byte by byte to see at which point it actually hangs. The BufferedInputStream may be hanging waiting to read more before returning what it has already read.

Upvotes: 2

Related Questions