为什么 Chrome 不呈现从套接字输出流中获取的页面? Java

Why Chrome is not rendering the page which it gets from socket output stream? Java

这是我的代码:

import java.net.*;
import java.io.*;

class Server
{
     public static void main(String args[])
     {
          try
          {
                ServerSocket svr = new ServerSocket(8900);
                System.out.println("waiting for request");
                Socket s = svr.accept();
                System.out.println("got a request");
                InputStream in = s.getInputStream();
                OutputStream out = s.getOutputStream();

                int x;
                byte data[]= new byte[1024];

                x = in.read(data);

                String response  = "<html><head><title>HTML content via java socket</title></head><body><h2>Hi! Every Body.</h2></body></html>";
                out.write(response.getBytes());
                out.flush();

                s.close();
                svr.close();
                System.out.println("closing all");
          }
          catch(Exception ex)
          {
                System.out.println("Err : " + ex);
          }
     }
}

运行 它我希望去 Chrome 对这个 : 127.0.0.1:8900 并得到漂亮的 html,但实际上 Chrome 是说以下:

This page isn’t working 127.0.0.1 sent an invalid response. ERR_INVALID_HTTP_RESPONSE.

而我的 Server.java 是我想要的 运行。 Eclipse 中的控制台在连接后显示得很好:

waiting for request got a request closing all.

所以我很卡。请帮我弄清楚。

chrome 您写的回复肯定不可读。因为它不包含有关 header

中响应的任何信息

您的代码实际上是发送响应。您可以使用 curl 进行检查。 以下代码将帮助您在 chrome.

中获得响应
        ServerSocket svr = new ServerSocket(8900);
        System.out.println("waiting for request");
        Socket s = svr.accept();
        System.out.println("got a request");
        InputStream in = s.getInputStream();
        OutputStream out = s.getOutputStream();

        int x;
        byte data[] = new byte[1024];

        x = in.read(data);

        String t = "HTTP/1.1 200 OK\r\n";
        byte[] bb = t.getBytes("UTF-8");
        out.write(bb);

        t = "Content-Length: 124\r\n";
        bb = t.getBytes("UTF-8");
        out.write(bb);
        t = "Content-Type: text/html\r\n\r\n";
        bb = t.getBytes("UTF-8");
        out.write(bb);

        String response = "<html><head><title>HTML content via java socket</title></head><body><h2>Hi! Every Body.</h2></body></html>";
        out.write(response.getBytes("UTF-8"));

        t = "Connection: Closed";
        bb = t.getBytes("UTF-8");
        out.write(bb);

        out.flush();

        s.close();
        svr.close();
        System.out.println("closing all");

重要的是如果你改变你的 response 那么你必须计算 Content-Length: 因为它将是你的 response byte[] 的长度并且Connection: Closed 字符串的 byte[].