Java Socket HTML响应

hel*_*922 5 html java sockets http

我正在尝试使用Java套接字向浏览器发送简单的HTML响应.

这是我的Java代码:

    Socket socket = server.accept();
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String s;
    // this is a test code which just reads in everything the requester sends
    while ((s = in.readLine()) != null)
    {
        System.out.println(s);
        if (s.isEmpty())
        {
            break;
        }
    }
    // send the response to close the tab/window
    String response = "<script type=\"text/javascript\">window.close();</script>";

    PrintWriter out = new PrintWriter(socket.getOutputStream());
    out.println("HTTP/1.1 200 OK");
    out.println("Content-Type: text/html");
    out.println("Content-Length: " + response.length());
    out.println();
    out.println(response);
    out.flush();
    out.close();
    socket.close();
Run Code Online (Sandbox Code Playgroud)

server 是一个ServerSocket设置为自动选择要使用的开放端口.

这个想法是任何重定向到http:\\localhost:port(port端口server正在监听的地方)的网页会自动关闭.

当此代码运行时,我的浏览器会收到响应,并且我已经验证它收到了我正在发送的所有信息.

但是,窗口/选项卡没有关闭,我甚至无法通过手动向window.close();我的浏览器的Javascript控制台发出命令来关闭选项卡.

我在这里错过了什么?我知道具有给定内容的html页面应该会自动关闭窗口/选项卡,那么为什么这不起作用呢?我正在Google Chrome上对此进行测试.

我已经尝试了一个更完整的html网页,但仍然没有运气.

以下是浏览器作为页面源报告的内容:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">window.close();</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

hel*_*922 0

总结一下评论:

根本问题实际上是在这里发现的,其中 window.close() 不会关闭当前窗口/选项卡。

我查了一下MDN 文档,发现了这个:

调用此方法时,引用的窗口将关闭。

仅允许对使用 window.open 方法由脚本打开的窗口调用此方法。如果窗口不是由脚本打开的,则 JavaScript 控制台中会出现以下错误:脚本可能无法关闭不是由脚本打开的窗口。

显然,Google Chrome 并未考虑脚本打开当前窗口。我也在 Firefox 中尝试过,它表现出相同的行为。

为了解决这个问题,我必须首先使用脚本打开当前窗口。

<script type="text/javascript">
    window.open('', '_self', '');
    window.close();
</script>
Run Code Online (Sandbox Code Playgroud)