为什么从套接字流中读取永久阻塞?

时间:2014-03-27 15:07:27

标签: java sockets http

我正在尝试通过打开TCP套接字手动执行一些HTTP,发送请求并读取/打印响应消息。响应体的内容打印得很好,但主线程永远不会退出并永久阻塞。

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"); 

我缺少什么,我该如何解决?

1 个答案:

答案 0 :(得分:1)

您确定要正确发送HTTP请求吗?这适合我。注意"连接:关闭\ r \ n"字符串很重要,否则在阅读内容后它也会挂起。

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"); 
    }

}