简体   繁体   中英

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?

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM