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

时间:2017-06-01 20:13:41

标签: java sockets google-chrome http serversocket

这是我的代码:

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

所以我很困惑。请帮我解决一下。

1 个答案:

答案 0 :(得分:1)

您正在撰写的回复肯定无法读取Chrome。因为它不包含有关标题中的响应的任何信息

您的代码实际上是发送回复。您可以使用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字节[]和字节[]的长度Connection: Closed字符串。