简体   繁体   中英

Why reading from a socket stream blocks forever?

I'm trying to do some HTTP manually by opening a TCP socket, send the request and read/print the response message. The content of the response body is well printed , but the main thread never exits and blocks forever.

socket = new Socket(host, port);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.print(request);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
reader.lines().forEach(System.out::println);
// String next_record = null;
// while ((next_record = reader.readLine()) != null)
// System.out.println(next_record);

socket.close();
// System.out.println("Finished"); 

What am I missing, and how can I fix it ?

Are you making sure you're sending the HTTP request correctly? This works for me. Note the "Connection: Close\\r\\n" string was important otherwise it hangs for me too after reading the content.

import java.net.Socket;
import java.io.PrintWriter;
import java.io.*;

public class App {

    public static void main(String[] args) throws Exception {
        String host = "google.com";
        int port = 80;
        Socket socket = new Socket(host, port);

        //BufferedWriter writer = new BufferedWriter(
        //       new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
        PrintWriter writer = new PrintWriter(socket.getOutputStream());
        writer.write("GET / HTTP/1.1\r\n");
        writer.write("Connection: Close\r\n");
        writer.write("\r\n");
        writer.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

        // reader.lines().forEach(System.out.println);
        String line;
        System.out.println("Reading lines:");
        while ((line = reader.readLine()) != null) {
            System.out.println("* " + line);
        }
        System.out.println("DONE READING RESPONSE");

        reader.close();
        writer.close();
        // socket.close();

        System.out.println("Finished"); 
    }

}

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