Java Socket HTML响应

时间:2012-11-22 02:35:29

标签: java html http sockets

我正在尝试使用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();

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

这个想法是重定向到http:\\localhost:port的任何网页(其中portserver正在侦听的端口)自动关闭。

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

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

我在这里缺少什么?我知道具有给定内容的html页面应该会自动关闭窗口/选项卡,那么为什么这不起作用呢?我正在Google Chrome上测试它。

我尝试过更完整的html网页,但仍然没有运气。

以下是浏览器报告的页面来源:

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

1 个答案:

答案 0 :(得分:0)

总结评论:

根问题实际上是找到here的问题,其中window.close()不会关闭当前窗口/标签。

我查了MDN Documentation并发现了这个:

  

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

     

只允许对使用window.open方法由脚本打开的窗口调用此方法。如果脚本未打开窗口,则JavaScript控制台中将显示以下错误:脚本可能无法关闭脚本未打开的窗口。

显然Google Chrome没有考虑脚本打开当前窗口。我也在Firefox中尝试过这种行为。

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

<script type="text/javascript">
    window.open('', '_self', '');
    window.close();
</script>