【问题标题】:Java Socket HTML responseJava 套接字 HTML 响应
【发布时间】:2012-11-23 02:46:27
【问题描述】:

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

【问题讨论】:

  • Context-Type 更正为Content-Type 会发生什么?
  • 如果window.close() 不能通过控制台工作,服务器不应该受到责备。尝试添加正确的doctype&lt;html&gt;&lt;head&gt; 标签。
  • 控制台中的 window.close() 对我有用。尝试包装&lt;html&gt;&lt;head&gt;
  • 试试 self.close()。另外,我看到了这个帖子:productforums.google.com/forum/#!topic/chrome/GjsCrvPYGlA。我正在使用 IE,但 window.close() 在浏览器中对我不起作用。但是,我尝试了 self.close() 并且成功了。
  • 这可能解释 window.close 问题:stackoverflow.com/questions/2032640/…。我改为 并且这有效。

标签: java html http sockets


【解决方案1】:

总结一下cmets:

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

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

当这个方法被调用时,被引用的窗口被关闭。

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

显然谷歌浏览器没有考虑脚本打开当前窗口。我也在 Firefox 中尝试过这个,它表现出相同的行为。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2016-09-29
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多