简体   繁体   English

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

[英]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. 我正在尝试通过打开TCP套接字手动执行一些HTTP,发送请求并读取/打印响应消息。 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? 您确定要正确发送HTTP请求吗? This works for me. 这对我有用。 Note the "Connection: Close\\r\\n" string was important otherwise it hangs for me too after reading the content. 请注意,“ Connection:Close \\ 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"); 
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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